根据多个条件替换熊猫数据框中的值

新手上路,请多包涵

基于此示例代码,我有一个相当简单的问题:

 x1 = 10*np.random.randn(10,3)
df1 = pd.DataFrame(x1)

I am looking for a single DataFrame derived from df1 where positive values are replaced with "up" , negative values are replaced with "down" , and 0 值(如果有)替换为 "zero" 。我尝试使用 .where().mask() 方法,但无法获得所需的结果。

我看过其他帖子一次根据多个条件进行过滤,但它们没有显示如何根据不同条件替换值。

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

阅读 354
2 个回答

通常,您可以在 np.select 上使用 values 并重新构建 DataFrame

 import pandas as pd
import numpy as np

df1 = pd.DataFrame(10*np.random.randn(10, 3))
df1.iloc[0, 0] = 0 # So we can check the == 0 condition

conds = [df1.values < 0 , df1.values > 0]
choices = ['down', 'up']

pd.DataFrame(np.select(conds, choices, default='zero'),
             index=df1.index,
             columns=df1.columns)

输出:

       0     1     2
0  zero  down    up
1    up  down    up
2    up    up    up
3  down  down  down
4    up    up    up
5    up    up    up
6    up    up  down
7    up    up  down
8  down    up  down
9    up    up  down

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

对于多种情况,即。 (df['employrate'] <=55) & (df['employrate'] > 50)

用这个:

 df['employrate'] = np.where(
   (df['employrate'] <=55) & (df['employrate'] > 50) , 11, df['employrate']
   )

或者你也可以这样做,

 gm.loc[(gm['employrate'] <55) & (gm['employrate'] > 50),'employrate']=11

这里的非正式语法可以是:

 <dataset>.loc[<filter1> & (<filter2>),'<variable>']='<value>'


 out[108]:
       country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   11.000000           7.29
2      Algeria   11.000000            .69
3      Andorra         nan          10.17
4       Angola   75.699997           5.57

因此我们在这里使用的语法是:

  df['<column_name>'] = np.where((<filter 1> ) & (<filter 2>) , <new value>, df['column_name'])


对于单一条件,即。 ( 'employrate'] > 70 )

        country        employrate alcconsumption
0  Afghanistan  55.7000007629394            .03
1      Albania  51.4000015258789           7.29
2      Algeria              50.5            .69
3      Andorra                            10.17
4       Angola  75.6999969482422           5.57

用这个:

 df.loc[df['employrate'] > 70, 'employrate'] = 7


        country  employrate alcconsumption
0  Afghanistan   55.700001            .03
1      Albania   51.400002           7.29
2      Algeria   50.500000            .69
3      Andorra         nan          10.17
4       Angola    7.000000           5.57

因此这里的语法是:

 df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]


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

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