我正在尝试根据另一列的条件创建一个新列。例如:我想根据事件计算一个“折扣价格”列。如果‘诗’申请10%的折扣,如果‘剧院’申请15%的折扣,否则,返回正常的价格。
# importing pandas as pd
import pandas as pd
# Creating the DataFrame
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Event':['Music', 'Poetry', 'Theater', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Create a new column 'Discounted_Price' after applying
# 10% discount on the existing 'Cost' column.
df['Discounted_Price'] = df['Cost'] - (0.1 * df['Cost']) 在我看来,这就像是(忽略语法):
df['Discounted_Price'] = if(df['Event']== 'Poetry') then df['Cost']*0.9,
elif (df['Event']== 'Theater') then df['Cost']*0.85诸若此类。
对如何做这个手术有什么建议吗?
发布于 2020-02-10 18:36:26
IIUC,您可以使用:
df:
Date Event Cost
0 10/2/2011 Music 10000
1 11/2/2011 Poetry 5000
2 12/2/2011 Theater 15000
3 13/2/2011 Comedy 2000您还可以使用np.where在一行中满足所有需求。
df['Discounted_Price'] = np.where(df.Event == 'Poetry', df['Cost']*0.9,
np.where(df.Event == 'Theater', df['Cost']*0.85, df['Cost']))现在的产出是:
Date Event Cost Discounted_Price
0 10/2/2011 Music 10000 10000.0
1 11/2/2011 Poetry 5000 4500.0
2 12/2/2011 Theater 15000 12750.0
3 13/2/2011 Comedy 2000 2000.0因此,它满足了else的要求,而不是获得NaNs,而是得到了所有的成本
df.loc[df['Event']=='Poetry','Discounted_Price']=df['Cost']*0.9
df.loc[df['Event']=='Theater','Discounted_Price']=df['Cost']*0.85输出:
Date Event Cost Discounted_Price
0 10/2/2011 Music 10000 NaN
1 11/2/2011 Poetry 5000 4500.0
2 12/2/2011 Theater 15000 12750.0
3 13/2/2011 Comedy 2000 NaN编辑
您还可以使用select(如@sammmywammy建议的那样)来解决手头的问题。我设计了以下语句,可以帮助您解决多列上的多个条件。
conditions = [
(df['Event'] == 'Music'),
(df['Event'] == 'Theater'),
(df['Event'] == 'Poetry'),
(df['Event'] == 'Comedy')]
choices = [(df['Cost']*0.9),(df['Cost']*0.85),(df['Cost']*0.7), (df['Cost']*0.5)]
df['Discounted'] = np.select(conditions, choices, default='null')对于多列的单次计算,上述查询转换为
conditions = [
(df['Event'] == 'Music'),
((df['Event'] == 'Theater') | (df['Event'] == 'Comedy')),
(df['Event'] == 'Poetry')]
choices = [(df['Cost']*0.9),(df['Cost']*0.85),(df['Cost']*0.7), ]
df['Discounted'] = np.select(conditions, choices, default='null')https://stackoverflow.com/questions/60156199
复制相似问题