pandas針對(duì)excel處理的實(shí)現(xiàn)
本文主要介紹了pandas針對(duì)excel處理的實(shí)現(xiàn),分享給大家,具體如下:
讀取文件
import padas df = pd.read_csv("") #讀取文件 pd.read_clipboard() #讀取粘貼板的內(nèi)容 #解決數(shù)據(jù)顯示不完全的問(wèn)題 pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) #獲取指定單元格的值 datefirst = config.iloc[0,1] datename = config.iloc[0,2] #新建一列two,篩選料號(hào)一列的前倆個(gè) sheet["two"] = sheet["料號(hào)"].apply(lambda x:x[:2])
數(shù)值處理
df["dog"] = df["dog"].replace(-1,0) #數(shù)值替換 #apply理解函數(shù)作為一個(gè)對(duì)象,可以作為參數(shù)傳遞給其它參數(shù),并且能作為函數(shù)的返回值 df["price_new"] = df["price"].apply(lambda pri:pyi.lower()) #新列對(duì)老列處理 df["pricee"] = df["price"] *2 #新列
獲取數(shù)據(jù)
data = df.head() #默認(rèn)讀取前行 df = pd.read_excel("lemon.xlsx",sheet_name=["python","student"]) #可以通過(guò)表單名同時(shí)讀取多個(gè) df = pd.read_excel("lemon.clsx",sheet_name=0) data = df.values #獲取所有的數(shù)據(jù) print("獲取到所有的值:\n{0}".format(data)) #格式化輸出 df = pd.read_excel("lemon.xlsx") data = df.ix[0].values #表示第一行,不包含表頭 print("獲取到所有的值:\n{0}".format(data)) #格式化輸出
loc和iloc詳解
loc[row,cloumn] 先行后列 : 是全部行或列,一般多行可以用中括號(hào),連續(xù)的可以用a:c等 iloc[index,columns] 行索引,列索引,索引都是從0開(kāi)始,用法是一樣的
多行
多行嵌套 df = pd.read_excel("lemon.xlsx") data = df.loc[1,2] #讀取指定多行的話,就要在ix[]里面嵌套列表指定行數(shù) print("獲取到所有的值:\n{0}".format(data)) #格式化輸出 多行 df=pd.read_excel('lemon.xlsx') data=df.ix[1,2]#讀取第一行第二列的值,這里不需要嵌套列表 print("讀取指定行的數(shù)據(jù):\n{0}".format(data)) 多行多列嵌套 df=pd.read_excel('lemon.xlsx') data=df.ix[[1,2],['title','data']].values#讀取第一行第二行的title以及data列的值,這里需要嵌套列表 print("讀取指定行的數(shù)據(jù):\n{0}".format(data)) 獲取所有行和指定列 df=pd.read_excel('lemon.xlsx') data=df.ix[:,['title','data']].values#讀所有行的title以及data列的值,這里需要嵌套列表 print("讀取指定行的數(shù)據(jù):\n{0}".format(data))
輸出行號(hào)和列號(hào)
輸出行號(hào)并打印輸出 df=pd.read_excel('lemon.xlsx') print("輸出行號(hào)列表",df.index.values) 輸出結(jié)果是: 輸出行號(hào)列表 [0 1 2 3] 輸出列名并打印輸出 df=pd.read_excel('lemon.xlsx') print("輸出列標(biāo)題",df.columns.values) 運(yùn)行結(jié)果如下所示: 輸出列標(biāo)題 ['case_id' 'title' 'data'] 獲取指定行數(shù)的值 df=pd.read_excel('lemon.xlsx') print("輸出值",df.sample(3).values)#這個(gè)方法類(lèi)似于head()方法以及df.values方法 輸出值 [[2 '輸入錯(cuò)誤的密碼' '{"mobilephone":"18688773467","pwd":"12345678"}'] [3 '正常充值' '{"mobilephone":"18688773467","amount":"1000"}'] [1 '正常登錄' '{"mobilephone":"18688773467","pwd":"123456"}']]
獲取指定值
獲取指定列的值 df=pd.read_excel('lemon.xlsx') print("輸出值\n",df['data'].values) excel數(shù)據(jù)轉(zhuǎn)字典 df=pd.read_excel('lemon.xlsx') test_data=[] for i in df.index.values:#獲取行號(hào)的索引,并對(duì)其進(jìn)行遍歷: #根據(jù)i來(lái)獲取每一行指定的數(shù)據(jù) 并利用to_dict轉(zhuǎn)成字典 row_data=df.ix[i,['case_id','module','title','http_method','url','data','expected']].to_dict() test_data.append(row_data) print("最終獲取到的數(shù)據(jù)是:{0}".format(test_data))
基本格式化
把帶有空值的行全部去除 df.dropna() 對(duì)空置進(jìn)行填充 df.fillna(value=0) df["price"].fillna(df["price".mean()]) 去除字符串兩邊的空格 df["city"] = df["city"].map(str.strip) 大小寫(xiě)轉(zhuǎn)換 df["city"] = df["city"].map(str.lower) 更改數(shù)據(jù)格式 df["price"].fillna(0).astype("int") 更改列的名稱(chēng) df.rename(columns={"category":"category_size"}) 刪除重復(fù)項(xiàng) df["city"].drop_duplicates() df["city"].drop_duplicates(keep="last") 數(shù)字修改和替換 df["city"].replace("sh","shanghai") 前3行數(shù)據(jù) df.tail(3) 給出行數(shù)和列數(shù) data.describe() 打印出第八行 data.loc[8] 打印出第八行[column_1]的列 data.loc[8,column_1] 第四到第六行(左閉右開(kāi))的數(shù)據(jù)子集 data.loc[range(4,6)] 統(tǒng)計(jì)出現(xiàn)的次數(shù) data[column_1].value_counts() len()函數(shù)被應(yīng)用在column_1列中的每一個(gè)元素上 map()運(yùn)算給每一個(gè)元素應(yīng)用一個(gè)的函數(shù) data[column_1].map(len).map(lambda x : x/100).plot() plot是繪圖 apply() 給一個(gè)列應(yīng)用一個(gè)函數(shù) applymap() 會(huì)給dataframe中的所有單元格應(yīng)用一個(gè)函數(shù) 遍歷行和列 for i,row in data.iterrows(): print(i,row) 選擇指定數(shù)據(jù)的行 important_dates = ['1/20/14', '1/30/14'] data_frame_value_in_set = data_frame.loc[data_frame['Purchase Date']\ .isin(important_dates), :] 選擇0-3列 import pandas as pd import sys input_file = r"supplier_data.csv" output_file = r"output_files\6output.csv" data_frame = pd.read_csv(input_file) data_frame_column_by_index = data_frame.iloc[:, [0, 3]] data_frame_column_by_index.to_csv(output_file, index=False) 添加行頭 import pandas as pd input_file = r"supplier_data_no_header_row.csv" output_file = r"output_files\11output.csv" header_list = ['Supplier Name', 'Invoice Number', \ 'Part Number', 'Cost', 'Purchase Date'] data_frame = pd.read_csv(input_file, header=None, names=header_list) data_frame.to_csv(output_file, index=False)
數(shù)據(jù)多表合并
數(shù)據(jù)合并 1.將表格通過(guò)concat()方法進(jìn)行合并 參數(shù)如下: objs(必須參數(shù)):參與連接的pandas對(duì)象的列表或字典 axis:指明連接的軸向,默認(rèn)為0 join:選中inner或outer(默認(rèn)),其它軸向上索引是按交集(inner)還是并集(outer)進(jìn)行合并 join_axes:指明用于其他N-1條軸的索引,不執(zhí)行并集/交集運(yùn)算 keys:與連接對(duì)象有關(guān)的值,用于形成連接軸向上的層次化索引 verify_integrity:是否去重 ignore_index:是否忽略索引 合并: eg: frames = [df1,df2,df3] result = pd.concat(frames) result = pd.concat(frames,keys=["x","y","z"]) #把每張表來(lái)個(gè)定義
新增df4表,橫向連接到df1表的第2367列,空置補(bǔ)nan index:是新增的行 axis=1是指列 df4 = pd.DataFrame(["B":["sf"],"D":["'sf],index=[2,3,6,7]]) result = pd.concat([df1,df4],axis=1)
將df1和df4橫向進(jìn)行交集合并 result = pd.concat([df1,df4],axis=1,join="inner") 列是增加,行是交集 按照df1的索引進(jìn)行df1表和df4表的橫向索引 pd.concat([df1,df4],axis=1,join_axes=[df1.index]) 列是增加,行以df1為準(zhǔn),空的為NaN 通過(guò)append()方法連接表格 result = df1.append(df2) result = df1.append(df4,ignore_index=True) 空格Nan補(bǔ)充 新增一列s1表,并且跟df1進(jìn)行橫向合并 s1 = pd.Series(["1","2","3","4"],name="x") result = pd.concat([df1,s1],axis=1) name是列,serise是一維列表,沒(méi)有name,他會(huì)用索引0開(kāi)始繼續(xù)填充 pd.concat([df1,s1],axis=1,ignore_index=True) 表格合并后不保留原來(lái)的索引列名 將key作為兩張表連接的中介 result = pd.merge(left,right,on="key") result = pd.merge(right,left,on=["key1","key2"]) key1和key2,只要有相同值就行,最后的排列是大的值為key1,小的key2 通過(guò)左表索引連接右表 right = pd.DataFrame({"key1":["K0","K2","K1","K2"], "key2":["K0","K1","K0","K0"], "C":["C0","C1","C2","C3"], "D":["D0","D1","D2","D3"]}, index = ["k0","k1","k2"]) result = left.join(right) 以做索引為基準(zhǔn),right沒(méi)有左索引的用Nan填充 result = left.join(right,how='outer') how:連接方式 on屬性在merge中,以k為中心拼接,有相同的就拼 result = pd.merge(left,right,on="K") result = pd.merge(left,right,on="K",suffixes=["_l","_r"]) 更改拼接后的neme屬性
# 解決顯示不完全的問(wèn)題 pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) config = pd.read_excel("C:\\Users\\Administrator\\Desktop\\數(shù)據(jù)\\文件名配置.xlsx", dtype=object) datefirst = config.iloc[0, 1] datename = config.iloc[0, 2] dateall = datefirst + r"\\" + datename textfile = config.iloc[1, 1] textname = config.iloc[1, 2] textall = textfile + r"\\" + textname sheet = pd.read_excel(dateall, sheet_name="Sheet2", dtype=object) sheet["two"] = sheet["料號(hào)"].apply(lambda x: x[:2]) # 取出不包含的數(shù)據(jù) df = sheet[~sheet["two"].isin(["41", "48"])] df1 = df[~df["檢驗(yàn)結(jié)果"].isin(["未驗(yàn)", "試產(chǎn)驗(yàn)證允收"])] # 刪除不需要的列 result = df1.iloc[:, :len(df1.columns) - 1] # 取出包含的數(shù)據(jù) DTR561 = result[result["機(jī)種"].isin(["DTR561"])] DTR562 = result[result["機(jī)種"].isin(["DTR562"])] HPS322 = result[result["機(jī)種"].isin(["HPS322"])] HPS829 = result[result["機(jī)種"].isin(["HPS829"])] writer = pd.ExcelWriter("C:\\Users\\Administrator\\Desktop\\數(shù)據(jù)\\數(shù)據(jù)篩選.xlsx") result.to_excel(writer, sheet_name="全部機(jī)種", index=False) DTR561.to_excel(writer, sheet_name="DTR561", index=False) DTR562.to_excel(writer, sheet_name="DTR562", index=False) HPS322.to_excel(writer, sheet_name="HPS322", index=False) HPS829.to_excel(writer, sheet_name="HPS829", index=False) writer.save() print("Data filtering completed")
到此這篇關(guān)于pandas針對(duì)excel處理的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)pandas excel處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 教你使用Pandas直接核算Excel中的快遞費(fèi)用
- Python入門(mén)之使用pandas分析excel數(shù)據(jù)
- pandas讀取excel時(shí)獲取讀取進(jìn)度的實(shí)現(xiàn)
- pandas快速處理Excel,替換Nan,轉(zhuǎn)字典的操作
- pandas讀取excel,txt,csv,pkl文件等命令的操作
- python pandas模糊匹配 讀取Excel后 獲取指定指標(biāo)的操作
- 關(guān)于Python 解決Python3.9 pandas.read_excel(‘xxx.xlsx‘)報(bào)錯(cuò)的問(wèn)題
- 解決使用Pandas 讀取超過(guò)65536行的Excel文件問(wèn)題
- 利用Python pandas對(duì)Excel進(jìn)行合并的方法示例
- Python pandas對(duì)excel的操作實(shí)現(xiàn)示例
- pandas to_excel 添加顏色操作
- 解決python pandas讀取excel中多個(gè)不同sheet表格存在的問(wèn)題
- Python pandas如何向excel添加數(shù)據(jù)
- pandas中的ExcelWriter和ExcelFile的實(shí)現(xiàn)方法
- pandas實(shí)現(xiàn)excel中的數(shù)據(jù)透視表和Vlookup函數(shù)功能代碼
- Python使用Pandas讀寫(xiě)Excel實(shí)例解析
- pandas將多個(gè)dataframe以多個(gè)sheet的形式保存到一個(gè)excel文件中
- 利用python Pandas實(shí)現(xiàn)批量拆分Excel與合并Excel
相關(guān)文章
python讀取圖片的方式,以及將圖片以三維數(shù)組的形式輸出方法
今天小編就為大家分享一篇python讀取圖片的方式,以及將圖片以三維數(shù)組的形式輸出方法,具有好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07Python解決pip install時(shí)出現(xiàn)的Could not fetch URL問(wèn)題
這篇文章主要介紹了Python解決pip install時(shí)出現(xiàn)的Could not fetch URL問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08python中的elasticsearch_dsl查詢(xún)語(yǔ)句轉(zhuǎn)換成es查詢(xún)語(yǔ)句詳解
這篇文章主要介紹了python中的elasticsearch_dsl查詢(xún)語(yǔ)句轉(zhuǎn)換成es查詢(xún)語(yǔ)句詳解,ElasticSearch在實(shí)際生產(chǎn)里通常和LogStash,Kibana,F(xiàn)ileBeat一起構(gòu)成Elastic?Stack來(lái)使用,它是這些組件里面最核心的一個(gè),需要的朋友可以參考下2023-07-07Python統(tǒng)計(jì)單詞出現(xiàn)的次數(shù)
最近經(jīng)理交給我一項(xiàng)任務(wù),統(tǒng)計(jì)一個(gè)文件中每個(gè)單詞出現(xiàn)的次數(shù),列出出現(xiàn)頻率最多的5個(gè)單詞。本文給大家?guī)?lái)了python 統(tǒng)計(jì)單詞次數(shù)的思路解析,需要的朋友參考下吧2018-04-04詳解Python如何使用audioflux處理音頻數(shù)據(jù)
Python的audioflux庫(kù)是一個(gè)處理音頻數(shù)據(jù)的強(qiáng)大工具,旨在提供簡(jiǎn)單而強(qiáng)大的接口,用于音頻信號(hào)處理、分析和合成,下面就跟隨小編一起來(lái)學(xué)習(xí)一下它的具體使用吧2023-06-06python實(shí)現(xiàn)請(qǐng)求數(shù)據(jù)包簽名
這篇文章主要介紹了python實(shí)現(xiàn)請(qǐng)求數(shù)據(jù)包簽名,主要以python怎么快速對(duì)請(qǐng)求體做一次簽名為主題,塑造實(shí)現(xiàn)請(qǐng)求數(shù)據(jù)包簽名過(guò)程,具有一定得參考價(jià)值,需要的小伙伴可以參考一下2022-02-02Python入門(mén)教程(三十四)Python的文件處理
這篇文章主要介紹了Python入門(mén)教程(三十四)Python的文件處理,在Python中處理文件的主要是open()函數(shù),接下來(lái)我們就來(lái)一起看看open()函數(shù)的用法吧,需要的朋友可以參考下2023-05-05