Pandas DataFrame将列相乘并创建新列

时间:2017-03-03 19:27:51

标签: python python-3.x pandas dataframe

我有一些有11列的数据。我需要将第1-10列乘以第11列,然后使用这些结果创建10个新列。为此,我使用pandas DataFrame。

现在我了解如何使用像这样的代码单独为每个列执行此操作

df['newcolumn1'] = df['column1']*df['column11']
df['newcolumn2'] = df['column2']*df['column11']
df['newcolumn3'] = df['column3']*df['column11']

我假设我可以设置一个函数和一个循环来迭代列并创建新列。无论如何,我可以通过引用列索引号而不是列名来执行此操作。

1 个答案:

答案 0 :(得分:3)

您可以使用multiply生成新列的DataFrame,然后使用pd.concat将各个列连接在一起,而不是单独或显式循环。按照您希望的列号进行操作可能看起来像

pd.concat([df, 
           (df.iloc[:, :10].multiply(df.iloc[:, -1], axis='rows')
                           .add_prefix('new_'))], 
           axis=1)

最小例子

>>> df
   column1  column2  column3  column4
0        0        1        2        3
1        4        5        6        7
2        8        9       10       11
3       12       13       14       15

>>> pd.concat([df, 
                (df.iloc[:, :3].multiply(df.iloc[:, -1], axis='rows')
                               .add_prefix('new_')], axis=1))], 
                axis=1)

   column1  column2  column3  column4  new_column1  new_column2  new_column3
0        0        1        2        3            0            3            6
1        4        5        6        7           28           35           42
2        8        9       10       11           88           99          110
3       12       13       14       15          180          195          210
相关问题