1 from pandas import Series,DataFrame 2 import pandas as pd 3 import numpy as np 4 obj=Series([4.5,7.2,-5.3,3.6],index=['d','b','a','c']) 5 obj 6 7 #重新生成索引 8 obj2=obj.reindex(['a','b','c','d','e']) 9 obj2
1 #前向填充 2 obj3=Series(['blue','purple','yellow'],index=[0,2,4]) 3 obj3.reindex(range(6),method='ffill')
1 frame=DataFrame(np.arange(9).reshape((3,3)),index=['a','c','d'], 2 columns=['ohio','Texas','california']) 3 frame
1 frame2=frame.reindex(['a','b','c','d']) 2 frame2
1 states=['Texax','Utah','california'] 2 frame.reindex(columns=states)
1 #同时对行 列进行重新索引 而插值只能引用到行 2 frame.reindex(index=['a','b','c','d'],method='ffill', 3 columns=states)
reindex的参数说明如下:
1 #丢弃指定轴的项 2 obj=Series(np.arange(5.),index=['a','b','c','d','e']) 3 new_obj=obj.drop('c') 4 new_obj
obj.drop(['d','c'])
c:对于dataframe可以删除任意轴上的索引
1 #对于DataFrame可以删除任意轴的索引 2 data = DataFrame(np.arange(16).reshape((4,4)), 3 index=['ohio','colorado','utah','new york'], 4 columns=['one','two','three','four']) 5 #删除两个 6 data.drop(['colorado','ohio'])
a:Series中的索引类似与Numpy,但是不只是整数,索引字符
1 obj=Series(np.arange(4.),index=['a','b','c','d']) 2 obj['b']#1.0
b:按照整数,范围
1 obj[1]#1.0 2 obj[2:4]# 2 3
1 obj['b':'c']#b c 1 2
1 data=DataFrame(np.arange(16).reshape(4,4), 2 index=['ohio','colorado','mike','jason'], 3 columns=['one','two','three','four']) 4 data
data['two']#输出第二列+行号 也就是索引
1 data[['three','one']]
data[:2]#选取的是前面两行
data[data['three']>5]
data.ix['colorado',['two','three']]
data.ix[['colorado','jason'],[3,0,1]]
k:输出行mike
data.ix[2]
DataFrame索引总结
a:Series的加法
1 s1=Series([7.3,-2.5,3.4,1.5],index=['a','c','d','e']) 2 s2=Series([-2.1,3.6,-1.5,4,3.1],index=['a','c','e','f','g']) 3 s1+s2
df1=DataFrame(np.arange(9.).reshape((3,3)),columns=list('bcd'), index=['utah','ohio','colorado']) df2=DataFrame(np.arange(12.).reshape((4,3)),columns=list('bde'), index=['utah','ohio','colorado','oragen'])
df1+df2
c:在算术方法中填充值。比如说两个dataframe相加,其中一个不在的时候填充为0
1 #算术中进行填充 2 df1=DataFrame(np.arange(12.).reshape((3,4)),columns=list('abcd')) 3 df2=DataFrame(np.arange(20.).reshape((4,5)),columns=list('abcde')) 4 df1+df2
#使用df1的add方法 传入df2以及一个fill_value参数 df1.add(df2,fill_value=0)
5 DataFrame和Series之间的运算----->广播,也就是如果第一个数值-1,那么这个列都会减1
a:看一看一个二维数组和一行之间的差
arr=np.arange(12.).reshape((3,4))
arr[0]
arr-arr[0]
b:frame和series的运算
frame=DataFrame(np.arange(12.).reshape((4,3)),columns=list('bde'), index=['utah','ohio','texas','orogen']) series=frame.ix[0]
frame-series