如何在熊猫身上做到这一点:
我在单个文本列上有一个函数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 = 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
这对我来说很管用:
import pandas as pd
import numpy as np
future = pd.DataFrame(
pd.date_range('2022-09-01',periods=360),
columns=['date']
)
def featurize(datetime):
return pd.Series({
'month':datetime.month,
'year':datetime.year,
'dayofweek':datetime.dayofweek,
'dayofyear':datetime.dayofyear
})
future.loc[
:,['month','year','dayofweek','dayofyear']
] = future.date.apply(featurize)
future.head()
输出:
date month year dayofweek dayofyear
0 2022-09-01 9 2022 3 244
1 2022-09-02 9 2022 4 245
2 2022-09-03 9 2022 5 246
3 2022-09-04 9 2022 6 247
4 2022-09-05 9 2022 0 248