一、安裝pandas
pip install pandas
二、數據結構
pandas有兩種數據結構,這里篇幅主要講述DataFrame。
DataFrame相當於一種二維的數據模型,相當於excel表格中的數據,有橫豎兩種坐標,橫軸很Series 一樣使用index,豎軸用columns 來確定,在建立DataFrame 對象的時候,需要確定三個元素:數據,橫軸,豎軸。
三、DataFrame基本使用
本次案例使用的測試表單:https://pan.baidu.com/s/1xn6gdMlh0pWHa-pnVv2LqA
1 創建DataFrame數據
創建不是我們本次的重點,我們所直接使用下列讀取現有表的方法
2 讀取excel/csv,讀取到的數據在DataFrame具柄中進行處理
# 讀取test.xls,並指定sheet df = pd.DataFrame(pd.read_excel('test.xls',sheet_name='detail'))
3 抽取指定列名賦值給need_df
# 指定列名,將這一列賦值到package_num_df 這個具柄,並打印結果 need_df = df[['工廠','倉庫','捆包號','樹種','規格','賬面數量','賬面米數']] print(need_df)
4 在need_df的dataframe中篩選[捆包號]=J-0001-04,並打印結果
find_need_df = need_df.loc[need_df['捆包號'] == 'J-0001-04'] print(find_need_df)
5在df的dataframe中刪除label標簽=1 的數據並打印結果(dataframe只存在於內存中,並不會改變原來的excle表數據,可以通過將內容中的dataframe重新賦值給新表即可
#刪除行號=1的那一整行,axis默認=0,inplace默認=False(不刪除原來excel的數據) 標志為True的話就說明將存儲在內存中的df 行號為1進行刪除 res = df.drop(labels=1, axis=0, inplace=True) print(df)
find_need_df = need_df.loc[need_df['捆包號'] == '原來df數據

drop后df的數據

6寫入excel/csv
#安裝本地目錄,格式化制定文件名稱 wb_path = os.path.join(dir_path,'work_book') ctime = datetime.datetime.now().strftime('%Y%m%d_%H%M') df.to_excel('%s/%s_detail.xls'%(wb_path,ctime))
若遇到 # ModuleNotFoundError: No module named 'xlwt' ,則需要安裝xlwt模塊
find_need_df.to_csv('temp.csv', mode='a', encoding='gbk')
四、DataFrame增刪改查操作
1 創建練習案例dataframe
import pandas as pd import numpy as np data = {'city': ['Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen', 'Hangzhou', 'Chongqing'], 'year': [2016,2017,2016,2017,2016, 2016], 'population': [2100, 2300, 1000, 700, 500, 500]} frame = pd.DataFrame(data, columns = ['year', 'city', 'population', 'debt']) df1 = pd.DataFrame({'apts': [55000, 60000], 'cars': [200000, 300000], }, index=['Shanghai', 'Beijing']) df2 = pd.DataFrame({'apts': [25000, 20000], 'cars': [150000, 120000], }, index=['Hangzhou', 'Najing']) df3 = pd.DataFrame({'apts': [30000, 10000], 'cars': [180000, 100000], }, index=['Guangzhou', 'Chongqing']) df4 = pd.DataFrame({'apts': [55000, 60000, 58000], 'cars': [200000, 300000, 250000], 'cities': ['Shanghai', 'Beijing', 'Shenzhen']}) df5 = pd.DataFrame({'salaries': [10000, 30000, 30000, 20000, 15000], 'cities': ['Suzhou', 'Beijing', 'Shanghai', 'Guangzhou', 'Tianjin']}) # print(df1) # print(df2) # print(df3) # print(df4) # print(df5)
2 增
# frame.ix[0] = np.arange(4) # 在第0行添加新行,分別為0,1,2,3 # frame.insert(0, 'temp', frame.year) # 在第0列處添加新列,名為temp # frame.ix[:, 'xx'] = np.arange(6) # 在末尾添加列名=xx的新列 # df1.append(df2) # 往df1末尾添加df2形成一個新數據 # pd.concat([df1, df2, df3]) # 往末尾添加多個dataframe,復用原來的column # pd.concat([df1, df2, df3], axis=1,sort=False) #axis=1時,不復用其他df的colums,各自使用自己的colums橫向階梯式合並 # 按照關鍵字做並集 # result = pd.merge(df4, df5, on='cities') #按照關鍵字cities的值相等時,將數據做並集 # result2 = pd.merge(df4, df5, on='cities', how='outer') # 按colums作並集,然后其他數據依次並集填入,不存在的值置為NaN
3 刪
# del frame['year'] # 刪除year列 # frame = frame.drop(['city', 'debt'], axis=1) # 刪除多列,axis=1 表示x軸方向 # frame = frame.drop([0, 1, 2]) # 刪除dataframe索引= 0、1、2行 # # frame.dropna() # 刪除帶有Nan的行 # frame.dropna(axis=1, how='all') # 刪除全為Nan的列 # frame.dropna(axis=1, how='any') # 刪除帶有Nan的列 # frame.dropna(axis=0, how='all') # 刪除全為Nan的行 # frame.dropna(axis=0, how='any') # 刪除帶有Nan的行 默認選項為此
4 改
# 元素賦值 # frame.loc[0, 'city'] = 'YunCheng' # 將frame數據中 dataframe索引=0,colums=city 的值改為 YunCheng # frame.iloc[0, 0] = 2011 #將frame數據中,dataframe y軸索引=0,x軸索引=0的值改為2011(索引為主) # frame.at[0, 'city'] = 'YunCheng' # frame.iat[0, 0] = 2010 #將frame數據中,dataframe y軸索引=0,x軸索引=0的值改為 2010 # frame.fillna(value=1) # 用1替換NaN # 列賦值 # frame['year'] = 2000 #將year這一列的數值全部更改為2000 # frame.debt = np.arange(6) #將debt這一列的值按0-5 依次填入 # val = pd.Series([200, 300, 500]) #制作series二維數列, # frame['debt'] = val #將val依次填入debt這一列,剩余沒有被填充到的默認NaN # 行賦值 # val = pd.Series(['aa', 2000, 500], index=['city', 'year', 'population']) #制作二維數列 # frame.loc[0] = val #將val按照列 year city population的值分別新增到x軸首行,並將索引位置0,debt則置NaN
5 查
# frame.index # 查詢frame數據的所以y軸索引起止、步長 # frame.columns # 查詢frame數據的colums具體有哪些列 # frame.values # 查詢frame數據的值,按y軸索引,從0開始,每一行作為一個列表,共6行組成一個新的大列表 # 元素查找 # xx = frame.loc[0, 'city'] # 數據是什么類型,xx就是什么類型 # xx = frame.loc[[0], ['city']] # DataFrame類型 # 行查找 # df = frame.loc[0:2] # DataFrame數據 y軸索引切片0~2 顧首顧尾。 # df = frame.iloc[0:2] # DataFrame類型 y軸索引切片0~2 顧首不顧尾。 # df = frame[0:3] # DataFrame數據,y軸索引切片0~3 顧首不顧尾 # df = frame.ix[0] # Series類型 y軸索引為0,的那一行數據 # 列查找 # df = frame.loc[:, 'city'] # 切片查找,列為city的那一列 # df = frame.loc[:, ['city', 'population']] # 切片查找,列為city、population的那兩列形成新的dataframe # df = frame.iloc[:, 0:2] # DataFrames數據x軸切片, 索引為0~2 顧首不顧尾形成新的dataframe # df = frame['year'] # 將year那一列的所有值取出 # df = frame.year # Series類型 同上 # df = frame[['population', 'year']] # DataFrame類型 篩選population year兩列重新組合dataframe # df = frame.filter(regex='population|year') # 結果同上 # frame[frame.year > 2016] # 選擇frame.year中>2016的行 # res =frame[frame.year.isin(['2016', '2015'])] # DataFrame數據,篩選year= 2016 或者2015的數據 # res = frame[['city', 'year']][0:3] # DataFrame 篩選出city和year兩列,並按y軸 0~3 顧首不顧尾進行切片,重組成新的dataframe # 塊查找 # df = frame.iloc[0:2, 0:2] # DataFrame數據,按x軸 y軸分別進行索引0~2 顧首不顧尾的切片,並重組新的dataframe # 條件查找 # df = frame.year.notnull() # Series類型 判斷year列的值是否不為空 # df = frame['year'].notnull() # Series 同上 # df = frame[frame.year.notnull()] # DataFrame類型 按照year非空篩選之后的結果 # df = frame[frame.year.notnull()].values # ndarray類型,按照year非空篩選之后的結果,形成一個大列表 # df = frame[frame.year == 2016][frame.city == 'Beijing'] # DataFrame # df = frame.debt[frame.year == 2016][frame.city == 'Beijing'] # 使用多條件year=2016、city=Beijing查詢debt的值
五、數據透視表
話不多說,直接上例子說明下簡單的一個用法:
本次案例使用的測試表單:https://pan.baidu.com/s/1HZCN9wZ_6sSNSnbUZPViHQ
import pandas as pd import numpy as np df = pd.read_excel('./work_book/pandas_sheet.xlsx') pd.set_option('display.width', None) #解決pandas模塊會出現省略號的問題 # print(df.head()) #讀取前五行數據 df['Status'] = df['Status'].astype('category') df['Status'].cat.set_categories(['won','pending','presented','declined'], inplace=True) ### 例1: 均值運算數據透視 # 單索引為[Name]字段,account price quantity進行平均值運算 res_ave_1 = pd.pivot_table(df, index=['Name']) # print(res_ave_1) # 多索引為[Name],[Rep],[Manager]字段,account price quantity進行平均值運算 res_ave_2 = pd.pivot_table(df,index=['Name', 'Rep', 'Manager']) # print(res_ave_2) # 多索引為[Manager][Rep]字段,account price quantity進行平均值運算 res_ave_3 = pd.pivot_table(df, index=['Manager','Rep']) # print(res_ave_3) # 多索引為[Manager][Rep]字段,value為[Price]進行平均值運算 res_ave_4 = pd.pivot_table(df, index=['Manager','Rep'], values=['Price']) # print(res_ave_4) # 多索引為[Manager][Rep]字段,value為[Price]並使用numpy的mean方法,並計算對應數據量的長度 res_ave_5 = pd.pivot_table(df, index=['Manager','Rep'], values=['Price'], aggfunc=[np.mean, len]) # print(res_ave_5) ### 例2: 求和運算數據透視 # 表格從左往右,以[Manager]為第一索引,[Rep]為第二索引,表格最上面以[Price]為第一索引,二級索引以[Product]的明細分別展開, # 統計數據以數據求和,product 沒有的部分填充NaN(fill_value=0是將NaN填充為0),margins=True表示所有表進行所有項目合計求和 res_sum_1 = pd.pivot_table(df, index=['Manager','Rep'], values=['Price'], columns=['Product'], aggfunc=[np.sum], fill_value=0, margins=True) # print(res_sum_1) #表格從左往右,以[Manager]為第一索引,[status]為第二索引,表格上面以'均值'、'合計'、'單元格長度個數'三大項作為大列,大列中分別都以 # CPU Maintenance Monitor Software 作為明細項列分開進行單獨計算(NaN項以0填充) res_sum_2 = pd.pivot_table(df, index=['Manager', 'Status'], columns=['Product'], values=['Quantity', 'Price'], aggfunc={'Quantity':len, 'Price':[np.sum,np.mean]}, fill_value=0 ) # print(res_sum_2) ### 例3:數據透視表過濾 #上述透視表res_sum_2生成后,他就位於DataFrame中,所以可以進行標准的DataFrame函數對其進行過濾,以Manager為篩選字段,字段值=Debra Henley res_filter_1 = res_sum_2.query('Manager == ["Debra Henley"]') # print(res_filter_1)
