myt*_*der 3 python apply chaining assign pandas
>>> df
a b c ...
0 1 2
1 3 4
. ...
Run Code Online (Sandbox Code Playgroud)
我希望该b列加倍。我知道这个方法
>>> df['b'] *= 2
Run Code Online (Sandbox Code Playgroud)
我可以以方法链接方式执行此操作吗?我想更可爱!像这样的东西。
>>> (df.drop('c', 1)
.someMethodToReplaceBColumnValues())
Run Code Online (Sandbox Code Playgroud)
我有很多方法来清理数据,这是其中一种操作,我一直坚持这样做。我也碰到过,replace,set_value等,但我无法弄清楚如何。
我apply也尝试过方法,但它只返回应用该操作的列。所以我只得到b带有 apply 方法的列。如何进一步接近?
你可以试试assign:
df = pd.DataFrame({'a':[1,2,3],
'b':[4,5,6],
'c':[7,8,9]})
print (df)
a b c
0 1 4 7
1 2 5 8
2 3 6 9
print (df.drop('c', 1).assign(b=df.b*2))
a b
0 1 8
1 2 10
2 3 12
Run Code Online (Sandbox Code Playgroud)
print (df.drop('c', 1).apply(lambda x: x * 2 if x.name == 'b' else x))
a b
0 1 8
1 2 10
2 3 12
Run Code Online (Sandbox Code Playgroud)