如何基于多个条件填充Nan?

时间:2019-06-28 00:08:28

标签: python pandas numpy

我有这样的数据框:

       a    b    c
    0  €9K €78M €96M
    1  €0  €0   NaN
    2  €0  €0   NaN
    3  €0  €1K  NaN

我想基于['a']和['b']中的值来填充NaN,如下所示:

1) if df[['a','b']=="€0" then fill df['c] with '€0' when it's NaN
2) if df['a'] == '€0' & df['b'] =="€1k" then fill df['c] with '€1K' when it's NaN

我尝试应用夫妇认为我在堆栈溢出时看到的但我没有成功。

condition1=[(df['a'] =="€0") & (df['b'] =="€0") ]
condition2=[(df['a'] =="€0") & (df['b'] =="€1K") ]

for row in df['c']:
    if condition1 == True:
        df['c].fillna('€0', inplace=True)
    elif condition2 == True:
        df['c'].fillna('€1k', inplace=True)
    else:
        df['c']

所以它应该看起来像这样:

   a    b    c
0  €9K €78M €96M
1  €0  €0   €0
2  €0  €0   €0
3  €0  €1K  €1K

Ps:我知道关于这个主题有很多帖子,但是没有用,所以我为什么要发布我的问题

1 个答案:

答案 0 :(得分:0)

我们可以使用numpy select

condition1=(df['a'] =="€0") & (df['b'] =="€0") 
condition2=(df['a'] =="€0") & (df['b'] =="€1K") 
df.c=np.select([condition1,condition2],[df.a,df.b],default=df.c)
df
     a     b     c
0  €9K  €78M  €96M
1   €0    €0    €0
2   €0    €0    €0
3   €0   €1K   €1K