Issue
I am trying to rename column names from a DataFrame that have space in the name. DataFrame (df) consists of 45 columns and the majority have spaces in the name. For instance: df.column.values [1] = 'Date Release'
, and the name should be changed to 'Date_Release'
. I tried DataFrame.rename ()
and DataFrame.columns.values[]
but did not work. I would much appreciate it if you could help me to find out what I did wrong
for colmns in df:
if ' ' in colmns:
colmns_new = '_'.join(colmns.split())
df = df.rename (columns = {"\"%s\"" %colmns : "\"%s\"" %colmns_new})
else:
print (colmns)
print (df)
or this one:
for i in range (len(df.columns)):
old= df.columns.values[i]
if ' ' in old:
new = '_'.join(old.split())
df = df.columns.values[i] = ['%s' % new]
print ("\"%s\"" % new)
print (df)
Error: AttributeError: 'list' object has no attribute 'columns'
Solution
import pandas as pd
df.columns = [i.replace(' ','_') for i in df.columns]
Answered By - Mo Huss
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.