繁体   English   中英

Python Dataframe - 在选定的行和列上应用函数

[英]Python Dataframe - apply function on selected rows and columns

我有一个数据框df ,它有两列AB 有些行的A为 NaN 。 我想根据B列中的值将函数应用于A包含NaN行。

我试过类似的东西:

df.loc[df['A'].isnull(), 'A']=df['B'].apply(lambda x: func(x))

我知道这行不通,但找不到正确的方法。

IIUC 你可以这样做:

df.loc[df['A'].isnull(), 'A'] = df.loc[df['A'].isnull(), 'B'].map(func)
#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM