Thursday, February 21, 2019

How do I rename columns in a pandas DataFrame?

pandas3
In [11]:
import pandas as pd
In [12]:
ufo = pd.read_csv('http://bit.ly/uforeports')
In [13]:
ufo.head()
Out[13]:
City Colors Reported Shape Reported State Time
0 Ithaca NaN TRIANGLE NY 6/1/1930 22:00
1 Willingboro NaN OTHER NJ 6/30/1930 20:00
2 Holyoke NaN OVAL CO 2/15/1931 14:00
3 Abilene NaN DISK KS 6/1/1931 13:00
4 New York Worlds Fair NaN LIGHT NY 4/18/1933 19:00
In [14]:
ufo.columns
Out[14]:
Index(['City', 'Colors Reported', 'Shape Reported', 'State', 'Time'], dtype='object')
In [15]:
ufo.rename(columns = {'Colors Reported':'Colors_Reported', 'Shape Reported':'Shape_Reported'}, inplace=True)
In [16]:
ufo.columns
Out[16]:
Index(['City', 'Colors_Reported', 'Shape_Reported', 'State', 'Time'], dtype='object')
In [19]:
ufo_cols = ['city', 'colors reported', 'shape reported', 'state', 'time']
In [20]:
ufo.columns = ufo_cols
In [21]:
ufo.head()
Out[21]:
city colors reported shape reported state time
0 Ithaca NaN TRIANGLE NY 6/1/1930 22:00
1 Willingboro NaN OTHER NJ 6/30/1930 20:00
2 Holyoke NaN OVAL CO 2/15/1931 14:00
3 Abilene NaN DISK KS 6/1/1931 13:00
4 New York Worlds Fair NaN LIGHT NY 4/18/1933 19:00
In [26]:
ufo = pd.read_csv('http://bit.ly/uforeports', names=ufo_cols, header=0)
In [27]:
ufo.head()
Out[27]:
city colors reported shape reported state time
0 Ithaca NaN TRIANGLE NY 6/1/1930 22:00
1 Willingboro NaN OTHER NJ 6/30/1930 20:00
2 Holyoke NaN OVAL CO 2/15/1931 14:00
3 Abilene NaN DISK KS 6/1/1931 13:00
4 New York Worlds Fair NaN LIGHT NY 4/18/1933 19:00
In [28]:
ufo.columns
Out[28]:
Index(['city', 'colors reported', 'shape reported', 'state', 'time'], dtype='object')
In [29]:
ufo.columns = ufo.columns.str.replace(' ', '_')
In [30]:
ufo.columns
Out[30]:
Index(['city', 'colors_reported', 'shape_reported', 'state', 'time'], dtype='object')
In [ ]:
 

No comments:

Post a Comment