如何在 Pandas DataFrame 中应用 IF、else、else if 条件

新手上路,请多包涵

我的 pandas DataFrame 中有一列包含国家/地区名称。我想使用 if-else 条件在列上应用不同的过滤器,并且必须使用这些条件在该 DataFrame 上添加一个新列。

当前数据框:-

 Company Country
BV 	Denmark
BV 	Sweden
DC 	Norway
BV 	Germany
BV 	France
DC 	Croatia
BV 	Italy
DC 	Germany
BV 	Austria
BV 	Spain

我试过这个,但在这个过程中,我必须一次又一次地定义国家。

bookings_d2.loc[(bookings_d2.Country== ‘丹麦’) | (bookings_d2.Country== ‘挪威’), ‘国家’] = bookings_d2.Country

在 RI 目前正在使用这样的 if else 条件,我想在 python 中实现同样的事情。

R 代码示例 1:ifelse(bookings_d2\(COUNTRY_NAME %in% c('丹麦','德国','挪威','瑞典','法国','意大利','西班牙','德国','奥地利' ,'荷兰','克罗地亚','比利时'), as.character(bookings_d2\)COUNTRY_NAME),‘其他’) R 代码示例 2:ifelse(bookings_d2\(country %in% c('Germany'), ifelse(bookings_d2\)BOOKING_BRAND %in% c(‘BV’),‘Germany_BV’,‘Germany_DC’),bookings_d2$country)

预期数据框:-

 Company Country
BV 	Denmark
BV 	Sweden
DC 	Norway
BV 	Germany_BV
BV 	France
DC 	Croatia
BV 	Italy
DC 	Germany_DC
BV 	Others
BV 	Others

原文由 Arvind Pant 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

您可以使用:

示例1:使用——- loc Series.isinnumpy.where ~

 #removed Austria, Spain
L = ['Denmark','Germany','Norway','Sweden','France','Italy',
     'Germany','Netherlands','Croatia','Belgium']

df['Country'] = np.where(df['Country'].isin(L), df['Country'], 'Others')

选择:

 df.loc[~df['Country'].isin(L), 'Country'] ='Others'

例如 2:使用 numpy.select 或嵌套 np.where

 m1 = df['Country'] == 'Germany'
m2 = df['Company'] == 'BV'
df['Country'] = np.select([m1 & m2, m1 & ~m2],['Germany_BV','Germany_DC'], df['Country'])

选择:

 df['Country'] = np.where(~m1, df['Country'],
                np.where(m2, 'Germany_BV','Germany_DC'))
print (df)
  Company     Country
0      BV     Denmark
1      BV      Sweden
2      DC      Norway
3      BV  Germany_BV
4      BV      France
5      DC     Croatia
6      BV       Italy
7      DC  Germany_DC
8      BV      Others
9      BV      Others

原文由 jezrael 发布,翻译遵循 CC BY-SA 4.0 许可协议

不确定你到底想达到什么目的,但我想这大概是这样的:

 df=pd.DataFrame({'country':['Sweden','Spain','China','Japan'], 'continent':[None] * 4})

  country continent
0  Sweden      None
1   Spain      None
2   China      None
3   Japan      None

df.loc[(df.country=='Sweden') | ( df.country=='Spain'), 'continent'] = "Europe"
df.loc[(df.country=='China') | ( df.country=='Japan'), 'continent'] = "Asia"

  country continent
0  Sweden    Europe
1   Spain    Europe
2   China      Asia
3   Japan      Asia

您还可以使用 python 列表理解,如:

 df.continent=["Europe" if (x=="Sweden" or x=="Denmark") else "Other" for x in df.country]

原文由 visibleman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进