我對熊貓和蟒蛇相當陌生。我試圖回傳資料框中所有可能互動的幾個選定互動項,然后將它們作為 df 中的新功能回傳。
我的解決方案是使用 sklearn 計算感興趣的互動,PolynomialFeature()并將它們附加到 for 回圈中的 df。見示例:
import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures
np.random.seed(1111)
a1 = np.random.randint(2, size = (5,3))
a2 = np.round(np.random.random((5,3)),2)
df = pd.DataFrame(np.concatenate([a1, a2], axis = 1), columns = ['a','b','c','d','e','f'])
combinations = [['a', 'e'], ['a', 'f'], ['b', 'f']]
for comb in combinations:
polynomizer = PolynomialFeatures(interaction_only=True, include_bias=False).fit(df[comb])
newcol_nam = polynomizer.get_feature_names(comb)[2]
newcol_val = polynomizer.transform(df[comb])[:,2]
df[newcol_nam] = newcol_val
df
a b c d e f a e a f b f
0 0.0 1.0 1.0 0.51 0.45 0.10 0.00 0.00 0.10
1 1.0 0.0 0.0 0.67 0.36 0.23 0.36 0.23 0.00
2 0.0 0.0 0.0 0.97 0.79 0.02 0.00 0.00 0.00
3 0.0 1.0 0.0 0.44 0.37 0.52 0.00 0.00 0.52
4 0.0 0.0 0.0 0.16 0.02 0.94 0.00 0.00 0.00
另一種解決方案是運行
PolynomialFeatures(2, interaction_only=True, include_bias=False).fit_transform(df)
然后放棄我不感興趣的互動。但是,就性能而言,這兩個選項都不是理想的,我想知道是否有更好的解決方案。
uj5u.com熱心網友回復:
正如評論的那樣,您可以嘗試:
df = df.join(pd.DataFrame({
f'{x} {y}': df[x]*df[y] for x,y in combinations
}))
或者干脆:
for comb in combinations:
df[' '.join(comb)] = df[comb].prod(1)
輸出:
a b c d e f a e a f b f
0 0.0 1.0 1.0 0.51 0.45 0.10 0.00 0.00 0.10
1 1.0 0.0 0.0 0.67 0.36 0.23 0.36 0.23 0.00
2 0.0 0.0 0.0 0.97 0.79 0.02 0.00 0.00 0.00
3 0.0 1.0 0.0 0.44 0.37 0.52 0.00 0.00 0.52
4 0.0 0.0 0.0 0.16 0.02 0.94 0.00 0.00 0.00
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326423.html
上一篇:Python程式沒有被執行
