How to name Pandas Dataframe Columns automatically?
Asked Answered
S

2

5

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?

Smoot answered 29/2, 2020 at 1:26 Comment(0)
B
11
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.)

Brimful answered 29/2, 2020 at 1:39 Comment(2)
Might be worth doing ["F"+str(i+1) for i in range(df.shape[1])] that way you never need to explicitly write the number of columns.Atrophied
@ALollz, you're right, thanks, I'll probably add something as it into my answer.Brimful
S
0

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
Sissel answered 29/2, 2020 at 1:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.