简体   繁体   English

Python:在 for 循环中创建新列名

[英]Python: Creating new column names in a for loop

I am trying to make custom column header names for the dataframe using a for loop.我正在尝试使用 for 循环为 dataframe 制作自定义列 header 名称。 Currently I am using two for loops to iterate through a dataframe, but don't know how to put new column headers in without hardcoding them.目前我正在使用两个 for 循环来遍历 dataframe,但不知道如何在不对其进行硬编码的情况下放入新的列标题。 I have我有

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

In df, the first column is taken and multiplied to the second, third, and fourth.在 df 中,取第一列并乘以第二、第三和第四列。 And then the code takes the second, and multiples it by the third and fourth, and continues in the for loop so the output columns are 'A B', 'A C', 'A D', 'B C', 'B D', and 'C D'.然后代码采用第二个,并将其乘以第三个和第四个,并在 for 循环中继续,因此 output 列是“A B”、“A C”、“A D”、“B C”、“B D'和'C D'。

What could I add to my for loop to extract the column names so each column name of df1 can be 'Long A, Short B', 'Long A, Short C'.... and finally 'Long C, Short D'我可以在我的 for 循环中添加什么来提取列名,以便 df1 的每个列名可以是“长 A,短 B”,“长 A,短 C”......最后是“长 C,短 D”

Thanks for your help谢谢你的帮助

from itertools import combinations
for x,y in combinations(df.columns,2):
    df['Long '+x+' Short '+y]=df[x]*df[y]
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

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

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