【问题标题】:replace values in a pandas dataframe (excluding missing values)替换熊猫数据框中的值(不包括缺失值)
【发布时间】:2018-07-08 20:49:37
【问题描述】:

我一直试图让我的代码正常工作,但我在这里遇到了一些问题。如果有人可以帮助我,那就太好了

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 以使不是 Coffee、Muffin 或 null 的每个值都变为“Other”?

  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 中添加空语句

【问题讨论】:

  • “让我的代码工作” - 请包含您的代码。
  • 是 NaN 还是空字符串?它们不是一回事。
  • 它是空白的,根据df.describe()缺少值

标签: python pandas numpy null conditional


【解决方案1】:

你快到了。如果您使用的是 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

【讨论】:

    【解决方案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'
    

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

      • df.loc[df.Col2.isin(['Coffee', 'Muffin',pd.np.nan]) == False,'Col2']='Other'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 2021-05-27
      • 1970-01-01
      • 2018-09-29
      • 2020-06-06
      相关资源
      最近更新 更多