【问题标题】:Python: Creating new column names in a for loopPython:在 for 循环中创建新列名
【发布时间】:2021-01-20 02:25:47
【问题描述】:

我正在尝试使用 for 循环为数据框创建自定义列标题名称。目前我正在使用两个 for 循环来遍历数据帧,但不知道如何在不硬编码的情况下放入新的列标题。我有

df = pandas.DataFrame({
     'A':[5,3,6,9,2,4],
     'B':[4,5,4,5,5,4],
     'C':[7,8,9,4,2,3],
     'D':[1,3,5,7,1,0],})

result = []
for i in range(len(df.columns)):
         SelectedCol = (df.iloc[:,i])
         for c in range(i+1, len(df.columns)):
                result.append(((SelectedCol+1)/ (df.iloc[:,c]+1)))
            
df1 = pandas.DataFrame(result)
df1=df1.transpose()

在df中,取第一列并乘以第二、第三和第四列。然后代码采用第二个,并将其乘以第三个和第四个,并在 for 循环中继续,因此输出列是 'AB'、'AC'、'AD'、'BC'、'BD'和'CD '。

我可以在我的 for 循环中添加什么来提取列名,以便 df1 的每个列名可以是 'Long A, Short B' , 'Long A, Short C'.... 最后是 'Long C, Short D'

感谢您的帮助

【问题讨论】:

    标签: python pandas loops for-loop


    【解决方案1】:
    from itertools import combinations
    for x,y in combinations(df.columns,2):
        df['Long '+x+' Short '+y]=df[x]*df[y]
    

    【讨论】:

      【解决方案2】:
      import pandas
      from itertools import combinations
      df = pandas.DataFrame({
          'A': [5, 3, 6, 9, 2, 4],
          'B': [4, 5, 4, 5, 5, 4],
          'C': [7, 8, 9, 4, 2, 3],
          'D': [1, 3, 5, 7, 1, 0], })
      # get all col name
      for index, row in df.iteritems():
          print(index)
      # get all  combinations
      result = combinations(df.iteritems(), 2)
      # calc
      for name, data in result:
          _name = name[0] + data[0]
          _data = name[1] * data[1]
          df[_name] = _data
      print(df)
      
      A
      B
      C
      D
         A  B  C  D  AB  AC  AD  BC  BD  CD
      0  5  4  7  1  20  35   5  28   4   7
      1  3  5  8  3  15  24   9  40  15  24
      2  6  4  9  5  24  54  30  36  20  45
      3  9  5  4  7  45  36  63  20  35  28
      4  2  5  2  1  10   4   2  10   5   2
      5  4  4  3  0  16  12   0  12   0   0
      

      【讨论】:

        猜你喜欢
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        • 2013-01-27
        • 1970-01-01
        • 2015-12-08
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        相关资源
        最近更新 更多