JChat
JChat

Reputation: 814

How to name Pandas Dataframe Columns automatically?

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?

Upvotes: 5

Views: 8615

Answers (2)

MarianD
MarianD

Reputation: 14181

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

Upvotes: 11

Jamin
Jamin

Reputation: 1402

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

Upvotes: 0

Related Questions