Renaming Column Names in Pandas

Renaming column names in Pandas

Just assign it to the .columns attribute:

>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
$a $b
0 1 10
1 2 20

>>> df.columns = ['a', 'b']
>>> df
a b
0 1 10
1 2 20

How to change column names in pandas Dataframe using a list of names?

you could use

df.columns = ['Leader', 'Time', 'Score']

Renaming columns in pandas

You can just rename it directly, like:

df.columns = ['first', 'second', 'third']

In your case you can use:

df.columns = ['Special{i}'.format(i=i) for i in range(0, len(df.columns))]

renaming the column names in dataframe using some parts of original column name

You can achieve this with a single regex:

df.columns = df.columns.str.replace(r'.*?([^_]+:).+?([^_]+_[^_]+)@.*',
r'\1\2', regex=True)

output:

   mynumber  trial1:type_id  trial1:king_que  fer45:gul_har23  chb1:kaam_nix
0 11 4 0 4 2
1 20 5 2 5 1
2 25 42 3 42 1

To understand ho this works, you can check the regex demo.

Programmatic way to rename pandas column, insert '_'

You can use a generator expression combined with the string method replace() for this:

df = pd.DataFrame({
'col 1': [1],
'col 2': [2],
'col 3': [3]
})

df.columns = (x.replace(' ', '_') for x in df.columns)


Related Topics



Leave a reply



Submit