如何在熊猫身上做到这一点:
我在单个文本列上有一个函数extract_text_features,返回多个输出列。具体来说,该函数返回6个值。
该函数可以工作,但是似乎没有任何合适的返回类型(pandas DataFrame/ numpy数组/ Python列表),以便输出可以正确分配df。Ix [:,10:16] = df.textcol.map(extract_text_features)
所以我认为我需要回落到迭代与df.iterrows(),按此?
更新:
使用df.iterrows()迭代至少要慢20倍,因此我放弃并将该函数分解为6个不同的.map(lambda…)调用。
更新2:这个问题是在v0.11.0版本被问到的,在可用性df之前。在v0.16中改进了Apply或添加了df.assign()。因此,很多问题和答案都不太相关。
对我来说,这很有效:
输入df
df = pd.DataFrame({'col x': [1,2,3]})
col x
0 1
1 2
2 3
函数
def f(x):
return pd.Series([x*x, x*x*x])
创建2个新列:
df[['square x', 'cube x']] = df['col x'].apply(f)
输出:
col x square x cube x
0 1 1 1
1 2 4 8
2 3 9 27
只需使用result_type="expand"
df = pd.DataFrame(np.random.randint(0,10,(10,2)), columns=["random", "a"])
df[["sq_a","cube_a"]] = df.apply(lambda x: [x.a**2, x.a**3], axis=1, result_type="expand")
基于user1827356的答案,你可以使用df.merge一次性完成赋值:
df.merge(df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1})),
left_index=True, right_index=True)
textcol feature1 feature2
0 0.772692 1.772692 -0.227308
1 0.857210 1.857210 -0.142790
2 0.065639 1.065639 -0.934361
3 0.819160 1.819160 -0.180840
4 0.088212 1.088212 -0.911788
编辑:
请注意内存消耗大,速度慢:https://ys-l.github.io/posts/2015/08/28/how-not-to-use-pandas-apply/ !
这是我过去所做的
df = pd.DataFrame({'textcol' : np.random.rand(5)})
df
textcol
0 0.626524
1 0.119967
2 0.803650
3 0.100880
4 0.017859
df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))
feature1 feature2
0 1.626524 -0.373476
1 1.119967 -0.880033
2 1.803650 -0.196350
3 1.100880 -0.899120
4 1.017859 -0.982141
为完整性而编辑
pd.concat([df, df.textcol.apply(lambda s: pd.Series({'feature1':s+1, 'feature2':s-1}))], axis=1)
textcol feature1 feature2
0 0.626524 1.626524 -0.373476
1 0.119967 1.119967 -0.880033
2 0.803650 1.803650 -0.196350
3 0.100880 1.100880 -0.899120
4 0.017859 1.017859 -0.982141