第5章 Pandas入门
Series的创建
obj=pd.Series([4,7,-5,3]) # 创建Series对象
obj.values # 返回值 array([4,7,-5,3])
obj.index # 返回索引
可以指定index
obj2 = pd.Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
由字典类型数据生成
sdata = {
'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
obj3 = pd.Series(sdata)
states = ['California', 'Ohio', 'Oregon', 'Texas']
obj4 = pd.Series(sdata, index=states)
DataFrame的创建
data = {
'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002, 2003],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
frame = pd.DataFrame(data)
指定 index与columns
frame2 = pd.DataFrame(data, columns=['year', 'state', 'pop', 'debt'],
index=['one', 'two', 'three', 'four',
'five', 'six'])
基础操作:选取行与列!
frame2.columns
frame2['state'] # 法一:读取某一列
frame2.year # 法二:读取某一列
frame2.loc['three'] # 读取某一行
重建Series的索引 index
obj = pd.Series([4.5, 7.2, -5.3, 3.6], index=['d', 'b', 'a', 'c'])
obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e'])
删除行与列
obj = pd.Series(np.arange(5.), index=['a', 'b', 'c', 'd', 'e'])
obj
new_obj = obj.drop('c') # 删除Series中的值
new_obj
obj.drop(['d', 'c']) # 删除Series中的2个值
数据预处理操作:删除df的行与列
data = pd.DataFrame(np.arange(16).reshape((4, 4)),
index=['Ohio', 'Colorado', 'Utah', 'New York'],
columns=['one', 'two', 'three', 'four'])
# 删除df的行
data.drop(['Colorado', 'Ohio'])
# 删除df的列
data.drop('two', axis=1)
data.drop(['two', 'four'], axis='columns')
# 删除df的列,并覆盖原df
obj.drop('c', inplace=True)
dataframe的索引操作
data = pd.DataFrame(np.arange(16