来自 Pandas 的传递输出适用于多个列



如何将输出从apply传递到多个列?

import pandas as pd
import numpy as np
def someFunc(x, y):
return x**2, y**2
df = pd.DataFrame(data=np.random.random(size=(5, 4)), columns=['a', 'b', 'c', 'd'])    
df.loc[:, ['c', 'd']] = np.zeros((5, 2)) # can pass array to df
df.loc[:, ['c', 'd']] = df.apply(lambda row: someFunc(row.a, row.b), axis=1) 

在上面的例子中,我可以将array传递给两列,但apply的输出是元组的pd.series,返回错误:

ValueError: Must have equal len keys and value when setting with an iterable

我认为您需要返回Series

def someFunc(x, y):
return pd.Series([x**2, y**2])
df = pd.DataFrame(data=np.random.random(size=(5, 4)), columns=['a', 'b', 'c', 'd'])    
df[['c', 'd']] = df.apply(lambda row: someFunc(row.a, row.b), axis=1) 
print (df)
a         b         c         d
0  0.145095  0.164194  0.021052  0.026960
1  0.141085  0.515790  0.019905  0.266040
2  0.416814  0.364209  0.173734  0.132648
3  0.025355  0.490520  0.000643  0.240610
4  0.938705  0.690380  0.881166  0.476624

相关内容

最新更新