【问题标题】:Iterate over columns of Pandas dataframe and create new variables遍历 Pandas 数据框的列并创建新变量
【发布时间】:2021-01-16 14:33:34
【问题描述】:

我无法弄清楚如何迭代 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 的值。我不确定我错过了什么。

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

【问题讨论】:

    标签: python pandas nested-for-loop


    【解决方案1】:

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

    你可能想要类似的东西

    for e, n in zip(existing,new):
        df[n] = df[e]*2
    

    【讨论】:

      【解决方案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
      

      【讨论】:

        【解决方案3】:

        您可以将原始 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)]
        )
        

        【讨论】:

          猜你喜欢
          • 2021-04-14
          • 1970-01-01
          • 2021-02-21
          • 2023-02-04
          • 2021-07-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多