繁体   English   中英

遍历 Pandas dataframe 的列并创建新变量

[英]Iterate over columns of Pandas dataframe and create new variables

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

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

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

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

上面的代码实际上是在 dataframe 中创建了三个新变量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)]
)

暂无
暂无

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

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