Pandas Lambda功能与Nan支持

Tyl*_*ell 4 python lambda nan python-3.x pandas

我正在尝试在Pandas中编写一个lambda函数,检查Col1是否为Nan,如果是,则使用另一列的数据.我无法获得正确编译/执行的代码(如下所示).

import pandas as pd
import numpy as np
df=pd.DataFrame({ 'Col1' : [1,2,3,np.NaN], 'Col2': [7, 8, 9, 10]})  
df2=df.apply(lambda x: x['Col2'] if x['Col1'].isnull() else x['Col1'], axis=1)
Run Code Online (Sandbox Code Playgroud)

有没有人对如何使用lambda函数编写这样的解决方案有任何好主意,或者我是否超出了lambda的能力?如果没有,你有其他解决方案吗?谢谢.

jez*_*ael 11

你需要pandas.isnull检查标量是否NaN:

df = pd.DataFrame({ 'Col1' : [1,2,3,np.NaN],
                 'Col2' : [8,9,7,10]})  

df2 = df.apply(lambda x: x['Col2'] if pd.isnull(x['Col1']) else x['Col1'], axis=1)

print (df)
   Col1  Col2
0   1.0     8
1   2.0     9
2   3.0     7
3   NaN    10

print (df2)
0     1.0
1     2.0
2     3.0
3    10.0
dtype: float64
Run Code Online (Sandbox Code Playgroud)

但更好的是使用Series.combine_first:

df['Col1'] = df['Col1'].combine_first(df['Col2'])

print (df)
   Col1  Col2
0   1.0     8
1   2.0     9
2   3.0     7
3  10.0    10
Run Code Online (Sandbox Code Playgroud)

另一个解决方案Series.update:

df['Col1'].update(df['Col2'])
print (df)
   Col1  Col2
0   8.0     8
1   9.0     9
2   7.0     7
3  10.0    10
Run Code Online (Sandbox Code Playgroud)


Ger*_*ges 7

该问题的正确解决方法是:

df['Col1'].fillna(df['Col2'], inplace=True)
Run Code Online (Sandbox Code Playgroud)