I have a very wide dataframe with over 1000 columns with each column name being a number1-1000 in sequential order (so the 2nd column is 2, third column is 3 etc). I have a list of column names, that are positional, meaning if I can take my column list in the order I have it, and just replace entire index row of the dataframe with it, I'd have exactly what I need.
Is this possible?
CodePudding user response:
IIUC, you need:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.rand(3,3))
df.columns = ['Col A', 'Col B', 'Col C']
print(df)
Result:
Col A Col B Col C
0 0.497856 0.373009 0.719566
1 0.126019 0.823805 0.570156
2 0.588741 0.405167 0.557865
Alternative solution:
df.rename(columns={0: 'Col A', 1: 'Col B', 2: 'Col C'}, inplace=True)
CodePudding user response:
If df.columns = pd.Index(list_of_names)
doesn't work, you can use:
df = df.rename(dict(zip(df.columns, list_of_names)), axis=1)