溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python使用pandas處理excel文件轉(zhuǎn)為csv文件的方法示例

發(fā)布時(shí)間:2020-09-26 06:11:05 來(lái)源:腳本之家 閱讀:158 作者:yingchenwy 欄目:開(kāi)發(fā)技術(shù)

由于客戶提供的是excel文件,在使用時(shí)期望使用csv文件格式,且對(duì)某些字段內(nèi)容需要做一些處理,如從某個(gè)字段中固定的幾位抽取出來(lái),獨(dú)立作為一個(gè)字段等,下面記錄下使用acaconda處理的過(guò)程;

import pandas
 
df = pandas.read_excel("/***/***.xlsx")
 
df.columns = [內(nèi)部為你給你的excel每一列自定義的名稱](比如我給我的excel自定義列表為:
["url","productName","***",。。。,"***"])

(下面開(kāi)始你自己的表演,對(duì)每一列內(nèi)容進(jìn)行你自己需要的處理)

df["url"] = df["url"].str.replace("http", "https")
 
df["***"] = df["***"].str.replace("\n", " ")
 
df["stract_content"] = df["url"].str[-6:]

表演結(jié)束之后,就要保存了

df.drop_duplicates().fillna("").to_csv("/***/***.csv", index=False, encoding="utf-8", sep="\3")

上面為讀取路徑,下面為保存路徑

結(jié)束之后,可以通過(guò)

df.head(5)來(lái)查看結(jié)果前5個(gè),判斷處理結(jié)果是否符合你的預(yù)期即可; 

下面總結(jié)一下將List內(nèi)容存儲(chǔ)到excel和csv:

直接上代碼:

list存儲(chǔ)到csv文件:下面代碼使用codes包操作

with codecs.open("result.csv", "w", encoding="utf-8") as fw:
  for i in final_res:
    fw.write(u"\3".join([j if isinstance(j, unicode) else str(j).decode("utf-8") for j in i]) + "\n")

下面是使用pandas操作:

columns是字符串列表,作為表格的標(biāo)題頭

df = pandas.DataFrame(my_list)
df.columns = ["col1", "col2", ...]
df.to_excel("result.xlsx", index=False, encoding="utf-8")

也可以先存儲(chǔ)為csv文件,然后使用pandas轉(zhuǎn)化為excel:

with codecs.open("result.csv", "w", encoding="utf-8") as fw:
  for i in final_res:
    fw.write(u"\3".join([j if isinstance(j, unicode) else str(j).decode("utf-8") for j in i]) + "\n")
 
with pandas.ExcelWriter('result.xlsx') as ew:
  pandas.read_csv("result.csv", sep='\3').to_excel(ew, index=False, header=["文件名", "query調(diào)用時(shí)間", "調(diào)用ip", "調(diào)用類(lèi)型", "query結(jié)束時(shí)間", "行序號(hào)", "top5 sku", "文件總耗時(shí)"], sheet_name="result", encoding="utf-8")

或者:

with codecs.open("result.csv", "w", encoding="utf-8") as fw:
  for i in final_res:
    fw.write(u"\3".join([j if isinstance(j, unicode) else str(j).decode("utf-8") for j in i]) + "\n")
 
df = pandas.read_csv("result.csv", sep="\3")
df.columns = ["col1", "col2", ...]
df.to_excel("result.xlsx", index=False, encoding="utf-8")

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI