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

问题描述

我无法弄清楚如何迭代 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 Dataframe 是:

   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)]
)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...