迭代 Pandas 数据框的列并创建新变量

Iterate over columns of Pandas dataframe and create new variables

我无法弄清楚如何迭代 pandas 数据帧中的变量并对每个变量执行相同的算术函数。

我有一个数据框 df,其中包含三个数值变量 x1x2x3。我想通过将每个变量乘以 2 来创建三个新变量。这是我正在做的:

existing = ['x1','x2','x3']
new = ['y1','y2','y3']

for i in existing:
    for j in new:
        df[j] = df[i]*2

上面的代码实际上是在数据框中创建了三个新变量 y1y2y3。但是 y1y2 的值被 y3 的值覆盖,所有三个变量都具有相同的值,对应于 y3 的值。我不确定我错过了什么。

非常感谢任何指导/建议。谢谢。

您在这里循环了大约 9 次 - 每列 3 次,每次迭代都会覆盖前一次。

你可能想要像

这样的东西
for e, n in zip(existing,new):
    df[n] = df[e]*2

我会做一些更通用的事情

#existing = ['x1','x2','x3']
exisiting = df.columns
new = existing.replace('x','y') 
#maybe you need map+lambda/for for each existing string

for (ind_existing, ind_new) in zip(existing,new):
    df[new[ind_new]] = df[existing[ind_existing]]*2 
#maybe there is more elegant way by using pandas assign function

您可以将原始 DataFrame 与具有双倍值的列连接起来:

cols_to_double = ['x0', 'x1', 'x2']
new_cols = list(df.columns) + [c.replace('x', 'y') for c in cols_to_double]

df = pd.concat([df, 2 * df[cols_to_double]], axis=1, copy=True)
df.columns = new_cols

因此,如果您的输入 df 数据框是:

   x0  x1  x2  other0  other1
0   0   1   2       3       4
1   0   1   2       3       4
2   0   1   2       3       4
3   0   1   2       3       4
4   0   1   2       3       4

执行前面几行后,你得到:

   x0  x1  x2  other0  other1  y0  y1  y2
0   0   1   2       3       4   0   2   4
1   0   1   2       3       4   0   2   4
2   0   1   2       3       4   0   2   4
3   0   1   2       3       4   0   2   4
4   0   1   2       3       4   0   2   4

这里是创建代码 df:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    data=np.column_stack([np.full((5,), i) for i in range(5)]),
    columns=[f'x{i}' for i in range(3)] + [f'other{i}' for i in range(2)]
)