热线电话:13121318867

登录
2019-02-21 阅读量: 1090
pandas apply和inplace dataframe

我有类似下面的数据框,并希望在pandas中使用下面的def''apply method'更改如下结果df。

据我所知,'apply'方法使得系列不能替代原始df。

id a b

-------

a 1 4

b 2 5

c 6 2

if df['a'] > df['b'] :

df['a'] = df['b']

else :

df['b'] = df['a']

result df :

id a b

-------

a 4 4

b 5 5

c 6 6

解决办法:我不确定你需要什么,因为预期的输出与你的条件不同,在这里我只能修复你的代码

for x,y in df.iterrows():

if y['a'] > y['b']:

df.loc[x,'a'] = df.loc[x,'b']

else:

df.loc[x,'b'] = df.loc[x,'a']

df

Out[40]:

id a b

0 a 1 1

1 b 2 2

2 c 2 2

如果我正确理解你的问题

df.assign(**dict.fromkeys(['a','b'],np.where(df.a>df.b,df.a,df.b)))

Out[43]:

id a b

0 a 1 1

1 b 2 2

2 c 2 2

0.0000
1
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子