roune_67
roune_67

Reputation: 33

How can I rename multiple columns with numbers in python?

I have a data frame with ~2400 columns and I would like to rename all the columns from 1 to 2400.
My current columns names are numbers and almost all of them are duplicated.

I was trying something like that but it doesn't work :

# An example
import pandas as pd
# Create an example dataframe
data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'],'Score': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])

ncol = len(df.columns)
for col in df.columns :
    for i in range(ncol) :
        df.rename(columns={col: str(i)}, inplace=True)

Thank you in advance.

Upvotes: 3

Views: 1153

Answers (2)

Stefan
Stefan

Reputation: 42885

np.arange certainly works, but you could also just use a list comprehension:

df.columns = [i for i in range(len(df.columns))]

If you want them as strings, use [str(i) for i in range(len(df.columns))]

Upvotes: 1

EdChum
EdChum

Reputation: 393923

IIUC you can just do

df.columns = pd.Index(np.arange(1,len(df.columns)+1).astype(str)

So this just overwrites the columns with a new Index object generated from np.arange and we cast the dtype to str using astype

Example:

In [244]:
df = pd.DataFrame(np.random.randn(4,4))
df.columns

Out[244]:
RangeIndex(start=0, stop=4, step=1)

In [243]:
df.columns = pd.Index(np.arange(1,len(df.columns)+1)).astype(str)
df.columns

Out[243]:
Index(['1', '2', '3', '4'], dtype='object')

On your example:

In [245]:
data = {'Commander': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'Date': ['2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08', '2012, 02, 08'],'Score': [4, 24, 31, 2, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df.columns = pd.Index(np.arange(1,len(df.columns)+1)).astype(str)
df.columns

Out[245]:
Index(['1', '2', '3'], dtype='object')

Upvotes: 1

Related Questions