How to name Pandas Dataframe Columns automatically?

笑着哭i 提交于 2020-12-12 09:57:42

问题


I have a Pandas dataframe df with 102 columns. Each column is named differently, say A, B, C etc. to give the original dataframe following structure

         Column A.    Column B.  Column C.   ....
Row 1.    
Row 2.
---
Row n

I would like to change the columns names from A, B, C etc. to F1, F2, F3, ...., F102. I tried using df.columns but wasn't successful in renaming them this way. Any simple way to automatically rename all column names to F1 to F102 automatically, insteading of renaming each column name individually?


回答1:


df.columns=["F"+str(i) for i in range(1, 103)]

Note:

Instead of a “magic” number 103 you may use the calculated number of columns (+ 1), e.g.

  • len(df.columns) + 1, or
  • df.shape[1] + 1.

(Thanks to ALollz for this tip in his comment.)




回答2:


One way to do this is to convert it to a pair of lists, and convert the column names list to the index of a loop:

import pandas as pd
d = {'Column A': [1, 2, 3, 4, 5, 4, 3, 2, 1], 'Column B': [1, 2, 3, 4, 5, 4, 3, 2, 1], 'Column c': [1, 2, 3, 4, 5, 4, 3, 2, 1]}
dataFrame = pd.DataFrame(data=d)
cols = list(dataFrame.columns.values)                 #convert original dataframe into a list containing the values for column name
index = 1                                             #start at 1
for column in cols:
    cols[index-1] = "F"+str(index)                    #rename the column name based on index
    index += 1                                             #add one to index
vals = dataFrame.values.tolist()                      #get the values for the rows
newDataFrame = pd.DataFrame(vals,   columns=cols)     #create a new dataframe containing the new column names and values from rows
print(newDataFrame)

Output:

   F1  F2  F3
0   1   1   1
1   2   2   2
2   3   3   3
3   4   4   4
4   5   5   5
5   4   4   4
6   3   3   3
7   2   2   2
8   1   1   1


来源:https://stackoverflow.com/questions/60461198/how-to-name-pandas-dataframe-columns-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!