pandas基礎-Python3,pandas-python3
未完
for examples:
example 1:
1 # Code based on Python 3.x 2 # _*_ coding: utf-8 _*_ 3 # __Author: "LEMON" 4 5 import pandas as pd 6 7 d = pd.date_range('20170101', periods=7) 8 aList = list(range(1,8)) 9 10 df = pd.DataFrame(aList, index=d, columns=[' '])11 df.index.name = 'value'12 13 print('----------df.index---------')14 print(df.index)15 16 print('---------df.columns---------')17 print(df.columns)18 19 print('----------df.values---------')20 print(df.values)21 22 print('----------df.describe--------')23 print(df.describe)24 25 print('----------information details--------')26 print(df.head(2)) #擷取開始的n條記錄27 print(df.tail(3)) #後去最後的n條記錄28 print(df[3:5]) # df[a:b],擷取第a+1至第b-1的記錄
運行結果如下:
1 ----------df.index--------- 2 DatetimeIndex(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04', 3 '2017-01-05', '2017-01-06', '2017-01-07'], 4 dtype='datetime64[ns]', name='value', freq='D') 5 ---------df.columns--------- 6 Index([' '], dtype='object') 7 ----------df.values--------- 8 [[1] 9 [2]10 [3]11 [4]12 [5]13 [6]14 [7]]15 ----------df.describe--------16 <bound method NDFrame.describe of 17 value 18 2017-01-01 119 2017-01-02 220 2017-01-03 321 2017-01-04 422 2017-01-05 523 2017-01-06 624 2017-01-07 7>25 ----------information details--------26 27 value 28 2017-01-01 129 2017-01-02 230 31 value 32 2017-01-05 533 2017-01-06 634 2017-01-07 735 36 value 37 2017-01-04 438 2017-01-05 5
example 2:
1 # Code based on Python 3.x 2 # _*_ coding: utf-8 _*_ 3 # __Author: "LEMON" 4 5 from pandas import Series, DataFrame 6 import pandas as pd 7 8 data = {'state': ['Ohino', 'Ohino', 'Ohino', 'Nevada', 'Nevada'], 9 'year': [2000, 2001, 2002, 2001, 2002],10 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}11 12 df = DataFrame(data, index=list(range(1, 6)),13 columns=['year', 'state', 'pop', 'name'])14 print(df)15 16 print('\n', '---------------')17 print(list(df.ix[3]))18 19 print('\n', '---------------')20 print(list(df['year']))21 22 aList = ['1', '2', '3', '4']23 bList = ['aa', 'bb', 'cb', 'dd']24 cList = ['lemon', 'apple', 'orange', 'banana']25 26 d = {'num': aList, 'char': bList, 'fruit': cList}27 28 29 df1 = DataFrame(d, index=['a', 'b', 'c', 'd'])30 # df2 = DataFrame(bList)31 print('\n', '---------------')32 print(df1)33 #print(df1.num)34 35 print('\n', '---------------')36 print(df1.ix['b']) # 擷取索引號為 'b' 的行的資料37 38 39 print('\n', '---------------')40 print(df1.ix[:2, 1:3]) # 以切片形式擷取部分資料
運行結果如下:
1 year state pop name 2 1 2000 Ohino 1.5 NaN 3 2 2001 Ohino 1.7 NaN 4 3 2002 Ohino 3.6 NaN 5 4 2001 Nevada 2.4 NaN 6 5 2002 Nevada 2.9 NaN 7 8 --------------- 9 [2002, 'Ohino', 3.6000000000000001, nan]10 11 ---------------12 [2000, 2001, 2002, 2001, 2002]13 14 ---------------15 char fruit num16 a aa lemon 117 b bb apple 218 c cb orange 319 d dd banana 420 21 ---------------22 char bb23 fruit apple24 num 225 Name: b, dtype: object26 27 ---------------28 fruit num29 a lemon 130 b apple 2