Pandas DataFrame乘以列并创建新列 [英] Pandas DataFrame multiplying columns and creating new columns
问题描述
我有一些包含11列的数据.我需要将第1-10列乘以第11列,然后用这些结果创建10个新列.为此,我正在使用pandas DataFrame.
I have some data that has 11 columns. I need to multiply columns 1-10 by column 11 and then create 10 new columns with those results. To do this I am using pandas DataFrame.
现在,我了解了如何使用这样的代码分别为每一列执行此操作
Now I understand how to do this for each column individually with a code like this
df['newcolumn1'] = df['column1']*df['column11']
df['newcolumn2'] = df['column2']*df['column11']
df['newcolumn3'] = df['column3']*df['column11']
我假设我可以设置一个函数和一个循环来遍历各列并创建新的列.无论如何,我可以通过引用列索引号而不是列名来做到这一点.
I'm assuming I can set up a function and a loop to iterate through the columns and create the new columns. Is there anyway I can do this by referencing the column index number instead of the column names.
推荐答案
您可以使用 pd.concat
组合在一起.您可能希望按列号进行操作
Instead of multiplying individually or explicitly looping, you could use multiply
to generate a DataFrame of your new columns, then pd.concat
to join things together. Doing so by column number as you would like to may look like
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
这篇关于Pandas DataFrame乘以列并创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!