Python Dataframe-对选定行和列应用函数
我有一个数据帧Python Dataframe-对选定行和列应用函数,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据帧df,它有两列a和B。某些行的A为NaN。我想根据列B中的值,对a中的NaN行应用一个函数 我试过这样的方法: df.loc[df['A'].isnull(), 'A']=df['B'].apply(lambda x: func(x)) 我知道这行不通,但我想不出正确的方法 #This should work. df['A'] = df.apply(lambda x: func(x.B) if np.isnan(x.A) else x.A, axis=1) 设置 df=pd.
df
,它有两列a
和B
。某些行的A
为NaN。我想根据列B
中的值,对a
中的NaN
行应用一个函数
我试过这样的方法:
df.loc[df['A'].isnull(), 'A']=df['B'].apply(lambda x: func(x))
我知道这行不通,但我想不出正确的方法
#This should work.
df['A'] = df.apply(lambda x: func(x.B) if np.isnan(x.A) else x.A, axis=1)
设置
df=pd.DataFrame({'A': {0: 1.0, 1: 1.0, 2: np.nan, 3: np.nan, 4: np.nan, 5: 1.0, 6: 1.0, 7: 1.0},
'B': {0: 1, 1: 1, 2: 1, 3: 20, 4: 20, 5: 300, 6: 300, 7: 20}})
Out[765]:
A B
0 1.0 1
1 1.0 1
2 NaN 1
3 NaN 20
4 NaN 20
5 1.0 300
6 1.0 300
7 1.0 20
def func(x):
return x*x
解决方案
#check d.A for nan inside the lambda can call the function only when d.A is nan.
df['A'] = df.apply(lambda x: func(x.B) if np.isnan(x.A) else x.A, axis=1)
df
Out[769]:
A B
0 1.0 1
1 1.0 1
2 1.0 1
3 400.0 20
4 400.0 20
5 1.0 300
6 1.0 300
7 1.0 20
IIUC您可以这样做:
df.loc[df['A'].isnull(), 'A'] = df.loc[df['A'].isnull(), 'B'].map(func)
你怎么知道它不起作用?你收到错误消息了吗?如果是这样的话,请把它包括在你的问题中。它不起作用,因为等式两边的长度不匹配。如果你真的尝试了,你会感到惊讶。因为它确实有效。因为赋值表达式不是一个等式,所以它是有效的。谢谢。但我得到一个错误:输入类型不支持“isnan”。这是因为我的A列是字符串类型吗?A列的类型是什么?里面有什么?您可以通过“df.info()”检查列类型