0

I have a dataframe like below:

Column1    Column2    Column3    Column4

1             12          5           6

I want to create a dictionary with the column_name as keys i.e. Column1, Column2, Column3, Column4 and values as 1,2,3,4 (incremental values)

Post that, i want to transform my dataframe to below:

1             2          3             4

1             12          5           6

i.e. Column1 replaced by 1, Column2 replaced by 2 and so on......

Can someone help me out?

4 Answers4

1

IIUC, you can try this

d = {k: v for k, v in zip(df.columns, range(1, len(df.columns)+1))}    
Out[372]:
{'Column1': 1, 'Column2': 2, 'Column3': 3, 'Column4': 4}

After getting d, you can do

df.columns = df.columns.to_series().map(d).values

    1   2   3   4
0   1   12  5   6

Here we make use of map and turn df.columns into a pd.Series object.

Tai
  • 7,684
  • 3
  • 29
  • 49
1

No need for a dictionary, you can assign range objects to df.columns directly.

df.columns = range(1, len(df.columns) + 1)

df
   1   2  3  4
0  1  12  5  6

You can also use any of the .str methods on df.columns -

df.columns = df.columns.str.lstrip('Column')

Or,

df.columns = df.columns.str.replace('^Column', '')

df
   1   2  3  4
0  1  12  5  6
cs95
  • 379,657
  • 97
  • 704
  • 746
0

I think this codes will help you out:

import pandas as pd
import numpy as np
data = [{'column1': 1, 'column2': 12,'column3': 15, 'column4': 6}]
df = pd.DataFrame(data)
df.columns = range(1, len(df.columns) + 1)
print (df)

#the output goes like this :

df
   1   2  3  4
0  1  12  5  6
kannappan
  • 1
  • 2
0

You can do this:

import pandas as pd   
data = [{'column1': 1, 'column2': 12,'column3': 15, 'column4': 6}]
df = pd.DataFrame(data)
#dict of columns {'column1': 1, 'column2': 2, ...}
column_dict = dict(zip(df.columns, list(range(len(df.columns))+1)))
# rename dataframe columns using rename method
new_df = df.rename(columns=column_dict)

Or this:

# create a df without specify columns names 
# will generate columns as numbers from 0 to len(df.columns) - 1
new_df = pd.DataFrame(df.values)
# add 1 to starts by 1
new_df.columns = new_df.columns + 1
romulomadu
  • 627
  • 6
  • 9