繁体   English   中英

如何将所有列相互相乘

[英]How to multiply all columns with each other

我有一个 pandas dataframe,我想给它添加新功能,如下所示:

假设我有特征X_1,X_2,X_3 and X_4 ,然后我想添加X_1 * X_2, X_1 * X_3, X_1 * X_4 ,以及类似的X_2 * X_3, X_2 * X_4X_3 * X_4 我想添加它们,而不是替换原来的功能。

我怎么做?

for c1, c2 in combinations(df.columns, r=2):
    df[f"{c1} * {c2}"] = df[c1] * df[c2]

您可以采用每 r = 2 列的组合,将它们相乘并分配。

示例运行:

In [66]: df
Out[66]:
   x1  y1  x2  y2
0  20   5  22  10
1  25   8  27   2

In [67]: from itertools import combinations

In [68]: for c1, c2 in combinations(df.columns, r=2):
    ...:     df[f"{c1} * {c2}"] = df[c1] * df[c2]
    ...:

In [69]: df
Out[69]:
   x1  y1  x2  y2  x1 * y1  x1 * x2  x1 * y2  y1 * x2  y1 * y2  x2 * y2
0  20   5  22  10      100      440      200      110       50      220
1  25   8  27   2      200      675       50      216       16       54

通过sklearn.preprocessing.PolynomialFeatures另一种方式:

In [74]: df
Out[74]:
   x1  y1  x2  y2
0  20   5  22  10
1  25   8  27   2

In [75]: from sklearn.preprocessing import PolynomialFeatures

In [76]: poly = PolynomialFeatures(degree=2,
                                   interaction_only=True, 
                                   include_bias=False)

In [77]: poly.fit_transform(df)
Out[77]:
array([[ 20.,   5.,  22.,  10., 100., 440., 200., 110.,  50., 220.],
       [ 25.,   8.,  27.,   2., 200., 675.,  50., 216.,  16.,  54.]])

In [78]: new_columns = df.columns.tolist() + [*map(" * ".join,
                                                   combinations(df.columns, r=2))]

In [79]: df = pd.DataFrame(poly.fit_transform(df), columns=new_columns)

In [80]: df
Out[80]:
     x1   y1    x2    y2  x1 * y1  x1 * x2  x1 * y2  y1 * x2  y1 * y2  x2 * y2
0  20.0  5.0  22.0  10.0    100.0    440.0    200.0    110.0     50.0    220.0
1  25.0  8.0  27.0   2.0    200.0    675.0     50.0    216.0     16.0     54.0

假设都是整数 X_1、X_2、X_3 和 X_4。 您可以创建新的 nan 列,并可以在其中添加您想要的内容。

df['X_1multipleX_2'] = np.nan
df['X_1multipleX_2'] = df['X_1']*df['X_2'] #You can do it without first step.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM