python-pandas的基本用法05
阿新 • • 發佈:2019-02-11
pandas的基本用法05-索引
# -*- coding: utf-8 -*- import numpy as np from pandas import Series, DataFrame from numpy.core.defchararray import index print 'Series的索引,預設數字索引可以工作。' s = Series(np.arange(4.), index=['a','b','c','d']) print s[['a','b']] # a 0 # b 1 # dtype: float64 print s[[0,1,2]] # a 0 # b 1 # c 2 # dtype: float64 print s[s>1] # c 2 # d 3 # dtype: float64 print 'Series的陣列切片' print s['a':'c'] # a 0 # b 1 # c 2 # dtype: float64 print 'DataFrame的索引' df = DataFrame(np.arange(16).reshape(4,4), index = ['a', 'b','c','d'], columns=[1,2,3,4] ) print df # 1 2 3 4 # a 0 1 2 3 # b 4 5 6 7 # c 8 9 10 11 # d 12 13 14 15 print '列印列' print df[[1,2]] # 1 2 # a 0 1 # b 4 5 # c 8 9 # d 12 13 print '列印行' print df[:2] # 1 2 3 4 # a 0 1 2 3 # b 4 5 6 7 print df.ix[:2] # 1 2 3 4 # a 0 1 2 3 # b 4 5 6 7 print '指定索引和列' print df.ix[['a','b'], [1,2,3]] # 1 2 3 # a 0 1 2 # b 4 5 6 print df.ix[:'c', :3] # 1 2 3 # a 0 1 2 # b 4 5 6 # c 8 9 10 print '根據條件選擇' print df>3 # 1 2 3 4 # a False False False False # b True True True True # c True True True True # d True True True True print df[[1,2]]>3 # 1 2 # a False False # b True True # c True True # d True True df[df<3]=0 print df # 1 2 3 4 # a 0 0 0 3 # b 4 5 6 7 # c 8 9 10 11 # d 12 13 14 15 print df.T # a b c d # 1 0 4 8 12 # 2 0 5 9 13 # 3 0 6 10 14 # 4 3 7 11 15