Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change pandas DataFrame columns from int to string?

I would like to change a specific(using numeric index to choose the column) column name in a pandas dataframe from integer to a string.

But it gives me back: "ValueError: invalid literal for int() with base 10: ‘col2’"

import pandas as pd
import numpy as np

arr1=[]

header = ['NA']*6
header[0] = "NAME1"
header = pd.DataFrame(header).transpose()
arr1 = pd.DataFrame(np.arange(36).reshape(6,6))
m1 = pd.concat([header,arr1])
m1.reset_index(drop=True)
print(m1.shape)
print(m1)


##renaming columns:
m1.columns.values[0] = "col2"

How can I do this? thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use rename:

m1 = m1.rename(columns={0: 'col2'})
print(m1)

# Output
    col2   1   2   3   4   5
0  NAME1  NA  NA  NA  NA  NA
0      0   1   2   3   4   5
1      6   7   8   9  10  11
2     12  13  14  15  16  17
3     18  19  20  21  22  23
4     24  25  26  27  28  29
5     30  31  32  33  34  35
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading