pandas 在Python中,如何使用if和or语句在数据框中创建列?

im9ewurl  于 2022-11-05  发布在  Python
关注(0)|答案(1)|浏览(158)

我希望创建一个名为“分配编号1或2”的列,其逻辑如下:
如果发布存档时间(GMT)介于“1月22日”和“6月22日”之间,并且配置文件存档原因为“Offer Declined*”或“Withdrawed”,则分配1
以及
如果发布存档时间(GMT)介于“7月22日”和“12月22日”之间,并且配置文件存档原因为“Offer Declined*“或“Withdrawed”,则分配2?
我从下面开始:

df['Assign Number 1 or 2'] = ['1' if i = 'Offer Declined* ' or i = 'Withdrawn' else '0' for i in df['Profile Archive Reason']]
2admgd59

2admgd591#

使用带有apply和lambda函数:

import pandas as pd

def my_func(row):
    if row.bname == "textbook":
        return "something"
    if row.bname == "b":
        return "something_else"

    return "not_found"

books = [{"bname": "textbook", "weight": 500, "price": 800},
   {"bname": "notebook", "weight": 100, "price": 200},
   {"bname": "storybook", "weight": 700, "price": 1000},
   {"bname": "whatever", "weight": 500, "price": 1200}]

df = pd.DataFrame(books)

df["new_colums"] = df.apply(lambda x: my_func(x),axis=1)
print(df)

返回

bname  weight  price new_colums
0   textbook     500    800  something
1   notebook     100    200  not_found
2  storybook     700   1000  not_found
3   whatever     500   1200  not_found

相关问题