Skip to content Skip to sidebar Skip to footer

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.

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

Solution 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 nameindex = 1#start at 1for column in cols:
    cols[index-1] = "F"+str(index)                    #rename the column name based on indexindex += 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 rowsprint(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

Post a Comment for "How To Name Pandas Dataframe Columns Automatically?"