pandas DataFrame 索引(二)
构造DataFrame
from pandas import Series,DataFrame
import numpy as np
frame=DataFrame(np.arange(9).reshape((3,3)),index=['a','c','d'],columns=['ohio','texas','california'])
frame
Out[73]:
ohio texas california
a 0 1 2
c 3 4 5
d 6 7 8
按照索引提取
frame2=frame.reindex(['a','b','c','d'])
frame2
Out[75]:
ohio texas california
a 0.0 1.0 2.0
b NaN NaN NaN
c 3.0 4.0 5.0
d 6.0 7.0 8.0
按照columns 提取
states=['texas','utah','california']
frame.reindex(columns=states)
Out[76]:
texas utah california
a 1 NaN 2
c 4 NaN 5
d 7 NaN 8
按照索引和columns提取
states=['texas','utah','california']
frame.reindex(index=['a','b','c','d'],method='ffill',columns=states)
Out[77]:
texas utah california
a 1 NaN 2
b 1 NaN 2
c 4 NaN 5
d 7 NaN 8
简便方法
frame.ix[['a','b','c','d'],states]
Out[79]:
texas utah california
a 1.0 NaN 2.0
b NaN NaN NaN
c 4.0 NaN 5.0
d 7.0 NaN 8.0