pandas針對excel處理的實現(xiàn)
更新時間:2021年01月15日 09:52:45 作者:土色無塵
這篇文章主要介紹了pandas針對excel處理的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
本文主要介紹了pandas針對excel處理的實現(xiàn),分享給大家,具體如下:


讀取文件
import padas
df = pd.read_csv("") #讀取文件
pd.read_clipboard() #讀取粘貼板的內(nèi)容
#解決數(shù)據(jù)顯示不完全的問題
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,篩選料號一列的前倆個
sheet["two"] = sheet["料號"].apply(lambda x:x[:2])
數(shù)值處理
df["dog"] = df["dog"].replace(-1,0) #數(shù)值替換 #apply理解函數(shù)作為一個對象,可以作為參數(shù)傳遞給其它參數(shù),并且能作為函數(shù)的返回值 df["price_new"] = df["price"].apply(lambda pri:pyi.lower()) #新列對老列處理 df["pricee"] = df["price"] *2 #新列
獲取數(shù)據(jù)
data = df.head() #默認讀取前行
df = pd.read_excel("lemon.xlsx",sheet_name=["python","student"]) #可以通過表單名同時讀取多個
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] 先行后列 : 是全部行或列,一般多行可以用中括號,連續(xù)的可以用a:c等 iloc[index,columns] 行索引,列索引,索引都是從0開始,用法是一樣的
多行
多行嵌套
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))
輸出行號和列號
輸出行號并打印輸出
df=pd.read_excel('lemon.xlsx')
print("輸出行號列表",df.index.values)
輸出結(jié)果是:
輸出行號列表 [0 1 2 3]
輸出列名并打印輸出
df=pd.read_excel('lemon.xlsx')
print("輸出列標題",df.columns.values)
運行結(jié)果如下所示:
輸出列標題 ['case_id' 'title' 'data']
獲取指定行數(shù)的值
df=pd.read_excel('lemon.xlsx')
print("輸出值",df.sample(3).values)#這個方法類似于head()方法以及df.values方法
輸出值
[[2 '輸入錯誤的密碼' '{"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:#獲取行號的索引,并對其進行遍歷:
#根據(jù)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()
對空置進行填充
df.fillna(value=0)
df["price"].fillna(df["price".mean()])
去除字符串兩邊的空格
df["city"] = df["city"].map(str.strip)
大小寫轉(zhuǎn)換
df["city"] = df["city"].map(str.lower)
更改數(shù)據(jù)格式
df["price"].fillna(0).astype("int")
更改列的名稱
df.rename(columns={"category":"category_size"})
刪除重復項
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]
第四到第六行(左閉右開)的數(shù)據(jù)子集
data.loc[range(4,6)]
統(tǒng)計出現(xiàn)的次數(shù)
data[column_1].value_counts()
len()函數(shù)被應用在column_1列中的每一個元素上
map()運算給每一個元素應用一個的函數(shù)
data[column_1].map(len).map(lambda x : x/100).plot() plot是繪圖
apply() 給一個列應用一個函數(shù)
applymap() 會給dataframe中的所有單元格應用一個函數(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.將表格通過concat()方法進行合并 參數(shù)如下: objs(必須參數(shù)):參與連接的pandas對象的列表或字典 axis:指明連接的軸向,默認為0 join:選中inner或outer(默認),其它軸向上索引是按交集(inner)還是并集(outer)進行合并 join_axes:指明用于其他N-1條軸的索引,不執(zhí)行并集/交集運算 keys:與連接對象有關(guān)的值,用于形成連接軸向上的層次化索引 verify_integrity:是否去重 ignore_index:是否忽略索引 合并: eg: frames = [df1,df2,df3] result = pd.concat(frames) result = pd.concat(frames,keys=["x","y","z"]) #把每張表來個定義

新增df4表,橫向連接到df1表的第2367列,空置補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橫向進行交集合并
result = pd.concat([df1,df4],axis=1,join="inner") 列是增加,行是交集
按照df1的索引進行df1表和df4表的橫向索引
pd.concat([df1,df4],axis=1,join_axes=[df1.index]) 列是增加,行以df1為準,空的為NaN
通過append()方法連接表格
result = df1.append(df2)
result = df1.append(df4,ignore_index=True) 空格Nan補充
新增一列s1表,并且跟df1進行橫向合并
s1 = pd.Series(["1","2","3","4"],name="x")
result = pd.concat([df1,s1],axis=1) name是列,serise是一維列表,沒有name,他會用索引0開始繼續(xù)填充
pd.concat([df1,s1],axis=1,ignore_index=True) 表格合并后不保留原來的索引列名
將key作為兩張表連接的中介
result = pd.merge(left,right,on="key")
result = pd.merge(right,left,on=["key1","key2"])
key1和key2,只要有相同值就行,最后的排列是大的值為key1,小的key2
通過左表索引連接右表
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) 以做索引為基準,right沒有左索引的用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屬性




# 解決顯示不完全的問題
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["料號"].apply(lambda x: x[:2])
# 取出不包含的數(shù)據(jù)
df = sheet[~sheet["two"].isin(["41", "48"])]
df1 = df[~df["檢驗結(jié)果"].isin(["未驗", "試產(chǎn)驗證允收"])]
# 刪除不需要的列
result = df1.iloc[:, :len(df1.columns) - 1]
# 取出包含的數(shù)據(jù)
DTR561 = result[result["機種"].isin(["DTR561"])]
DTR562 = result[result["機種"].isin(["DTR562"])]
HPS322 = result[result["機種"].isin(["HPS322"])]
HPS829 = result[result["機種"].isin(["HPS829"])]
writer = pd.ExcelWriter("C:\\Users\\Administrator\\Desktop\\數(shù)據(jù)\\數(shù)據(jù)篩選.xlsx")
result.to_excel(writer, sheet_name="全部機種", 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針對excel處理的實現(xiàn)的文章就介紹到這了,更多相關(guān)pandas excel處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
- 教你使用Pandas直接核算Excel中的快遞費用
- Python入門之使用pandas分析excel數(shù)據(jù)
- pandas讀取excel時獲取讀取進度的實現(xiàn)
- pandas快速處理Excel,替換Nan,轉(zhuǎn)字典的操作
- pandas讀取excel,txt,csv,pkl文件等命令的操作
- python pandas模糊匹配 讀取Excel后 獲取指定指標的操作
- 關(guān)于Python 解決Python3.9 pandas.read_excel(‘xxx.xlsx‘)報錯的問題
- 解決使用Pandas 讀取超過65536行的Excel文件問題
- 利用Python pandas對Excel進行合并的方法示例
- Python pandas對excel的操作實現(xiàn)示例
- pandas to_excel 添加顏色操作
- 解決python pandas讀取excel中多個不同sheet表格存在的問題
- Python pandas如何向excel添加數(shù)據(jù)
- pandas中的ExcelWriter和ExcelFile的實現(xiàn)方法
- pandas實現(xiàn)excel中的數(shù)據(jù)透視表和Vlookup函數(shù)功能代碼
- Python使用Pandas讀寫Excel實例解析
- pandas將多個dataframe以多個sheet的形式保存到一個excel文件中
- 利用python Pandas實現(xiàn)批量拆分Excel與合并Excel
相關(guān)文章
Python批量將Word文檔(.doc)轉(zhuǎn)換為.docx格式的完整實現(xiàn)步驟
這篇文章主要介紹了Python批量將Word文檔(.doc)轉(zhuǎn)換為.docx格式的完整實現(xiàn)步驟,文中通過代碼介紹的非常詳細,適用于Windows系統(tǒng),解決了手動轉(zhuǎn)換的低效率和出錯率問題,需要的朋友可以參考下2024-12-12
4種Python基于字段的不使用元類的ORM實現(xiàn)方法總結(jié)
在 Python 中,ORM(Object-Relational Mapping)是一種將對象和數(shù)據(jù)庫之間的映射關(guān)系進行轉(zhuǎn)換的技術(shù),本文為大家整理了4種不使用元類的簡單ORM實現(xiàn)方式,需要的可以參考下2023-12-12
Python3.7安裝keras和TensorFlow的教程圖解
這篇文章主要介紹了Python3.7安裝keras和TensorFlow經(jīng)驗,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10
web.py在SAE中的Session問題解決方法(使用mysql存儲)
這篇文章主要介紹了web.py在SAE中的Session問題解決方法(使用mysql存儲),本文直接給出實現(xiàn)代碼,代碼中包含詳細注釋,需要的朋友可以參考下2015-06-06
python+opencv實現(xiàn)動態(tài)物體識別
這篇文章主要為大家詳細介紹了python+opencv實現(xiàn)動態(tài)物體識別,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01

