Tom*_*ard 3 python tuples dataframe pandas
我今天在工作中遇到了这个问题,我想知道是否有有效的方法来做到这一点。
基本上我有一个看起来像这样的数据框
df = pd.DataFrame([1,2,3], columns = ['a'])
Run Code Online (Sandbox Code Playgroud)
我还有一个返回元组的函数。(请注意,这只是一个最小的例子,我的问题是不同的)
compute = lambda x: (2*x, 3*x)
Run Code Online (Sandbox Code Playgroud)
我需要找到一种方法来做一些理想的事情,如下所示:
(df['b'], df['c']) = df['a'].apply(compute)
Run Code Online (Sandbox Code Playgroud)
不幸的是,这种语法不起作用,我无法想出另一种方法来做到这一点。
唯一类似的问题是这个 ,但解决方案似乎真的很“hacky”,我相信有更好的方法来做到这一点。
谢谢你!!
IIUC,你可以尝试:
compute = lambda x: (2*x, 3*x)
df[['b','c']]=pd.DataFrame(df.a.apply(compute).tolist()) #thanks harvpan
#df[['b','c']]=pd.DataFrame(df.a.apply(compute).values.tolist())
print(df)
Run Code Online (Sandbox Code Playgroud)
a b c
0 1 2 3
1 2 4 6
2 3 6 9
Run Code Online (Sandbox Code Playgroud)