替换pandas数据框中的值(不包括缺失值)

时间:2018-01-30 03:29:40

标签: python pandas numpy null conditional

我一直试图让我的代码工作,但我在这里遇到了一些麻烦。如果有人可以帮助我会很棒

DF

  Col1              Col2          
  2017-01-01        Coffee
  2017-01-01        Muffin
  2017-01-01        Donut
  2017-01-01        Toast
  2017-01-01        
  2017-01-01        

如何更改Col2,以便咖啡或松饼或空的每个值都变为“其他'?

  Col1              Col2          
  2017-01-01        Coffee
  2017-01-01        Muffin
  2017-01-01        Other
  2017-01-01        Other
  2017-01-01        
  2017-01-01 

编辑:

df.loc[~df.Col2.isin(['Coffee','Muffin']), 'Col2'] = 'Other'

^这就是我现在所处的位置,但是如何在isin中添加空语句

3 个答案:

答案 0 :(得分:3)

你快到了。如果您正在使用NaN,则需要使用isnull进行额外检查。创建一个掩码并使用loc -

设置值
m = ~(df.Col2.isin(['Coffee', 'Muffin']) | df.Col2.isnull())
df.loc[m, 'Col2'] = 'Other'

df

         Col1    Col2
0  2017-01-01  Coffee
1  2017-01-01  Muffin
2  2017-01-01   Other
3  2017-01-01   Other
4  2017-01-01     NaN
5  2017-01-01     NaN

或者,如果他们空白(空字符串,而不是NaN - 他们不同!),请对第二个条件执行相等比较 -

m = ~(df.Col2.isin(['Coffee', 'Muffin']) | df.Col2.eq(''))

以下是np.where / pd.Series.where / pd.Series.mask -

的更多可能性
df.Col2 = np.where(m, 'Other', df.Col2)

或者,

df.Col2 = df.Col2.where(~m, 'Other')

或者,

df.Col2 = df.Col2.mask(m, 'Other')

df

         Col1    Col2
0  2017-01-01  Coffee
1  2017-01-01  Muffin
2  2017-01-01   Other
3  2017-01-01   Other
4  2017-01-01     NaN
5  2017-01-01     NaN

答案 1 :(得分:2)

df = pd.DataFrame({'Col1':['2017-01-01','2017-01-01','2017-01-01','2017-01-01','2017-01-01','2017-01-01'],
 'Col2':['Coffee','Muffin','Donut','Toast',pd.np.nan,pd.np.nan]})

conditions = (df['Col2'] != 'Coffee') & (df['Col2'] != 'Muffin') & (df['Col2'].isnull() == False)

df['Col2'][conditions] = 'Other'

答案 2 :(得分:2)

isin可以包含np.nan

df.loc[df.Col2.isin(['Donut', 'Toast',np.nan]),'Col2']='Other'
df
Out[112]: 
         Col1    Col2
0  2017-01-01  Coffee
1  2017-01-01  Muffin
2  2017-01-01   Other
3  2017-01-01   Other
4  2017-01-01   Other
5  2017-01-01   Other
相关问题