pandas有兩個主要數據結構:Series,DataFramepython
import numpy as np from pandas import Series, DataFrame
Series是一種相似於一維數組的對象,它由一組數據(各類NumPy數據類型)以及一組與之相關的數據標籤(即索引)組成。數組
Series的字符串表現形式爲:索引在左邊,值在右邊。數據結構
①用數組生成Series
②指定Series的index
③使用字典生成Series
④使用字典生成Series,並額外指定index,不匹配部分爲NaN
⑤Series相加,相同索引部分相加
⑥指定Series及其索引的名字
⑦替換index
#!/usr/bin/evn python # -*- coding: utf-8 -*-
import pandas as pd from pandas import Series print ('①用數組生成Series') obj = Series([4, 7, -5, 3]) print(obj) print(obj.values) print(obj.index) print('=='*20) print('②指定Series的index') obj2 = Series([4, 7, -5, 3], index = ['d', 'b', 'a', 'c']) print(obj2) print(obj2.index) print(obj2['a']) obj2['d'] = 6
print(obj2[['c', 'a', 'd']]) print(obj2[obj2 > 0]) # 找出大於0的元素
print('b' in obj2) # 判斷索引是否存在
print('e' in obj2) print('=='*20) print('③使用字典生成Series') sdata = {'Ohio':45000, 'Texas':71000, 'Oregon':16000, 'Utah':5000} obj3 = Series(sdata) print(obj3) print('=='*20) print('④使用字典生成Series,並額外指定index,不匹配部分爲NaN。') states = ['California', 'Ohio', 'Oregon', 'Texas'] obj4 = Series(sdata, index = states) print(obj4) print('=='*20) print('⑤Series相加,相同索引部分相加。') print(obj3 + obj4) print('=='*20) print('⑥指定Series及其索引的名字') obj4.name = 'population' obj4.index.name = 'state'
print(obj4) print('=='*20) # print('⑦替換index') obj.index = ['Bob', 'Steve', 'Jeff', 'Ryan'] print(obj)
DataFrame是一個表格型的數據結構,它含有一組有序的列,每列能夠是不一樣的值類型(數值、字符串、布爾值等)。ide
①用字典生成DataFrame,key爲列的名字
②指定索引,在列中指定不存在的列,默認數據用NaN
③用Series指定要修改的索引及其對應的值,沒有指定的默認數據用NaN
④賦值給新列,刪除列
⑤DataFrame轉置
⑥指定索引順序,以及使用切片初始化數據
⑦指定索引和列的名稱
#!/usr/bin/evn python # -*- coding: utf-8 -*- import numpy as np from pandas import Series, DataFrame print('①用字典生成DataFrame,key爲列的名字。') data = {'state':['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year':[2000, 2001, 2002, 2001, 2002], 'pop':[1.5, 1.7, 3.6, 2.4, 2.9]} print(DataFrame(data)) print(DataFrame(data, columns = ['year', 'state', 'pop'])) # 指定列順序 print('②指定索引,在列中指定不存在的列,默認數據用NaN。') frame2 = DataFrame(data, columns = ['year', 'state', 'pop', 'debt'], index = ['one', 'two', 'three', 'four', 'five']) print(frame2) print(frame2['state']) print(frame2.year) print(frame2.ix['three']) frame2['debt'] = 16.5 # 修改一整列 print(frame2) frame2.debt = np.arange(5) # 用numpy數組修改元素 print(frame2) print('③用Series指定要修改的索引及其對應的值,沒有指定的默認數據用NaN。') val = Series([-1.2, -1.5, -1.7], index = ['two', 'four', 'five']) frame2['debt'] = val print(frame2) print('④賦值給新列') frame2['eastern'] = (frame2.state == 'Ohio') # 若是state等於Ohio爲True print(frame2) print(frame2.columns) print('⑤DataFrame轉置') pop = {'Nevada':{2001:2.4, 2002:2.9}, 'Ohio':{2000:1.5, 2001:1.7, 2002:3.6}} frame3 = DataFrame(pop) print(frame3) print(frame3.T) print('⑥指定索引順序,以及使用切片初始化數據。') print(DataFrame(pop, index = [2001, 2002, 2003])) print(frame3['Ohio'][:-1]) print(frame3['Nevada'][:2]) pdata = {'Ohio':frame3['Ohio'][:-1], 'Nevada':frame3['Nevada'][:2]} print(DataFrame(pdata)) print('⑦指定索引和列的名稱') frame3.index.name = 'year' frame3.columns.name = 'state' print(frame3) print(frame3.values) print(frame2.values)
能夠輸入給DataFrame構造器的數據函數
pandas的索引對象負責管理軸標籤和其餘元數據(好比軸名稱等)。構建Series或DataFrame時,所用到的任何數組或其餘序列的標籤都會被轉換成一個Index:spa
①獲取index
②使用Index對象
③判斷列和索引是否存在
#!/usr/bin/evn python # -*- coding: utf-8 -*- import numpy as np import pandas as pd import sys from pandas import Series, DataFrame, Index print('①獲取index') obj = Series(range(3), index = ['a', 'b', 'c']) index = obj.index print(index[1:]) try: index[1] = 'd' # index對象read only except: print(sys.exc_info()[0]) print('②使用Index對象') index = Index(np.arange(3)) obj2 = Series([1.5, -2.5, 0], index = index) print(obj2) print(obj2.index is index) print('③判斷列和索引是否存在') pop = {'Nevada':{20001:2.4, 2002:2.9}, 'Ohio':{2000:1.5, 2001:1.7, 2002:3.6}} frame3 = DataFrame(pop) print('Ohio' in frame3.columns) print('2003' in frame3.index)
pandas對象的一個重要方法是reindex,其做用是建立一個適應新索引的新對象。3d
對於DataFrame,reindex能夠修改(行)索引、列,或兩個都修改。若是僅傳入一個序列,則會從新索引行。code
①從新指定索引及順序
②從新指定索引並指定元素填充方法
③對DataFrame從新指定索引
④從新指定columns,使用columns關鍵字便可從新索引列
⑤對DataFrame從新指定索引(reindex,ix)並指定填元素充方法
#!/usr/bin/evn python # -*- coding: utf-8 -*- import numpy as np from pandas import DataFrame, Series print('①從新指定索引及順序') obj = Series([4.5, 7.2, -5.3, 3.6], index = ['d', 'b', 'a', 'c']) print(obj) obj2 = obj.reindex(['a', 'b', 'd', 'c', 'e']) print(obj2) print(obj.reindex(['a', 'b', 'd', 'c', 'e'], fill_value = 0)) # 指定不存在元素的默認值 print('②從新指定索引並指定元素填充方法') obj3 = Series(['blue', 'purple', 'yellow'], index = [0, 2, 4]) print(obj3) print(obj3.reindex(range(6), method = 'ffill')) #ffill能夠實現前向值填充 print('③對DataFrame從新指定索引') frame = DataFrame(np.arange(9).reshape(3, 3), index = ['a', 'c', 'd'], columns = ['Ohio', 'Texas', 'California']) print(frame) frame2 = frame.reindex(['a', 'b', 'c', 'd']) print(frame2) print('④從新指定column') states = ['Texas', 'Utah', 'California'] print(frame.reindex(columns = states)) print('⑤對DataFrame從新指定索引並指定填元素充方法') print(frame.reindex(index = ['a', 'b', 'c', 'd'], method = 'ffill', columns = states)) print(frame.ix[['a', 'b', 'd', 'c'], states])
reindex函數的參數對象
方法很簡單,只要有一個索引數組或者列表便可,drop方法返回的是一個在指定軸上刪除了指定值的新對象。blog
①Series根據索引刪除元素
②DataFrame刪除元素,可指定索引或列
#!/usr/bin/evn python # -*- coding: utf-8 -*- import numpy as np from pandas import Series, DataFrame print('①Series根據索引刪除元素') obj = Series(np.arange(5.), index = ['a', 'b', 'c', 'd', 'e']) new_obj = obj.drop('c') print(new_obj) print(obj.drop(['d', 'c'])) print('②DataFrame刪除元素,可指定索引或列。') data = DataFrame(np.arange(16).reshape((4, 4)), index = ['Ohio', 'Colorado', 'Utah', 'New York'], columns = ['one', 'two', 'three', 'four']) print(data) print(data.drop(['Colorado', 'Ohio'])) print(data.drop('two', axis = 1)) print(data.drop(['two', 'four'], axis = 1))
①Series的索引,默認數字索引能夠工做
②Series的數組切片
③DataFrame的索引
④根據條件選擇
#!/usr/bin/evn python # -*- coding: utf-8 -*- import numpy as np from pandas import Series, DataFrame print('①Series的索引,默認數字索引能夠工做。') obj = Series(np.arange(4.), index = ['a', 'b', 'c', 'd']) print(obj) print(obj['b']) print(obj[3]) print(obj[[1, 3]]) print(obj[obj < 2]) print('②Series的數組切片') print(obj['b':'c']) # 閉區間,這一點和python不一樣 obj['b':'c'] = 5 print(obj) print('③DataFrame的索引') data = DataFrame(np.arange(16).reshape((4, 4)), index = ['Ohio', 'Colorado', 'Utah', 'New York'], columns = ['one', 'two', 'three', 'four']) print(data) print(data['two']) # 打印列 print(data[['three', 'one']]) print(data[:2]) print(data.ix['Colorado', ['two', 'three']]) # 指定索引和列 print(data.ix[['Colorado', 'Utah'], [3, 0, 1]]) print(data.ix[2]) # 打印第2行(從0開始) print(data.ix[:'Utah', 'two']) # 從開始到Utah,第2列。 print('④根據條件選擇') print(data[data.three > 5]) print(data < 5) # 打印True或者False data[data < 5] = 0 print(data)
DataFrame的索引選項
①Series的加法
②DataFrame加法,索引和列都必須匹配
③數據填充
④DataFrame與Series之間的操做
#!/usr/bin/evn python # -*- coding: utf-8 -*- import numpy as np from pandas import Series, DataFrame print('①Series的加法') s1 = Series([7.3, -2.5, 3.4, 1.5], index = ['a', 'c', 'd', 'e']) s2 = Series([-2.1, 3.6, -1.5, 4, 3.1], index = ['a', 'c', 'e', 'f', 'g']) print(s1) print(s2) print(s1 + s2) print('②DataFrame加法,索引和列都必須匹配。') df1 = DataFrame(np.arange(9.).reshape((3, 3)), columns = list('bcd'), index = ['Ohio', 'Texas', 'Colorado']) df2 = DataFrame(np.arange(12).reshape((4, 3)), columns = list('bde'), index = ['Utah', 'Ohio', 'Texas', 'Oregon']) print(df1) print(df2) print(df1 + df2) print('③數據填充') df1 = DataFrame(np.arange(12.).reshape((3, 4)), columns = list('abcd')) df2 = DataFrame(np.arange(20.).reshape((4, 5)), columns = list('abcde')) print(df1) print(df2) print(df1.add(df2, fill_value = 0)) print(df1.reindex(columns = df2.columns, fill_value = 0)) print('④DataFrame與Series之間的操做') arr = np.arange(12.).reshape((3, 4)) print(arr) print(arr[0]) print(arr - arr[0]) frame = DataFrame(np.arange(12).reshape((4, 3)), columns = list('bde'), index = ['Utah', 'Ohio', 'Texas', 'Oregon']) series = frame.ix[0] print(frame) print(series) print(frame - series) series2 = Series(range(3), index = list('bef')) print(frame + series2) series3 = frame['d'] print(frame.sub(series3, axis = 0)) # 按列減