教你用Python實現(xiàn)Excel表格處理
一、文件
一個測試有兩個sheet頁的Excel測試文件 test.xlsx


二、代碼
import pandas as pd
file1 = pd.ExcelFile('D:\\data\\py\\test.xlsx')
file2 = pd.read_excel('D:\\data\\py\\test.xlsx')
print(file)
<pandas.io.excel._base.ExcelFile object at 0x0000021DE525DF88> -----------------分割線--------------------- 姓名 年齡 性別 住址 0 張三 7 男 NaN 1 李四 6 男 NaN 2 王芳 6 女 NaN
三、分析
pd.read_excel讀出來是一個dataframe可以直接打印出內(nèi)容,但是只能讀取一個sheet頁,默認第一個sheet頁
@Appender(_read_excel_doc)
@deprecate_kwarg("skip_footer", "skipfooter")
def read_excel(
io,
sheet_name=0,
header=0,
names=None,
index_col=None,
usecols=None,
squeeze=False,
dtype=None,
engine=None,
converters=None,
true_values=None,
false_values=None,
skiprows=None,
nrows=None,
na_values=None,
keep_default_na=True,
verbose=False,
parse_dates=False,
date_parser=None,
thousands=None,
comment=None,
skip_footer=0,
skipfooter=0,
convert_float=True,
mangle_dupe_cols=True,
**kwds
):
for arg in ("sheet", "sheetname", "parse_cols"):
if arg in kwds:
raise TypeError(
"read_excel() got an unexpected keyword argument " "`{}`".format(arg)
)
if not isinstance(io, ExcelFile):
io = ExcelFile(io, engine=engine)
elif engine and engine != io.engine:
raise ValueError(
"Engine should not be specified when passing "
"an ExcelFile - ExcelFile already has the engine set"
)
return io.parse(
sheet_name=sheet_name,
header=header,
names=names,
index_col=index_col,
usecols=usecols,
squeeze=squeeze,
dtype=dtype,
converters=converters,
true_values=true_values,
false_values=false_values,
skiprows=skiprows,
nrows=nrows,
na_values=na_values,
keep_default_na=keep_default_na,
verbose=verbose,
parse_dates=parse_dates,
date_parser=date_parser,
thousands=thousands,
comment=comment,
skipfooter=skipfooter,
convert_float=convert_float,
mangle_dupe_cols=mangle_dupe_cols,
**kwds
)
pd.ExcelFile 返回值是一個Excel對象,不能直接用,但是可以讀取整個Excel內(nèi)容
四、pd.ExcelFile
file = pd.ExcelFile('D:\\data\\py\\test.xlsx')
sheet頁名稱
print(file.sheet_names)
['一年級', '二年級']
遍歷讀取每個sheet頁的內(nèi)容
for name in file.sheet_names:
_df = pd.read_excel(file,name)
print(_df)
姓名 年齡 性別 住址 0 張三 7 男 NaN 1 李四 6 男 NaN 2 王芳 6 女 NaN 姓名 年齡 性別 0 李明 8 男 1 劉敏 8 女 2 張強 7 男
將兩個sheet頁的內(nèi)容合并,并添加一列內(nèi)容為sheet頁名稱
df_list=[]
for name in file.sheet_names:
_df = pd.read_excel(file,name)
_df['班級']=name
df_list.append(_df)
df = pd.concat([_df for _df in df_list],sort=False)
print(df)
姓名 年齡 性別 住址 班級 0 張三 7 男 NaN 一年級 1 李四 6 男 NaN 一年級 2 王芳 6 女 NaN 一年級 0 李明 8 男 NaN 二年級 1 劉敏 8 女 NaN 二年級 2 張強 7 男 NaN 二年級
忽略掉原來的index
df = pd.concat([_df for _df in df_list],ignore_index=True,sort=False) print(df)
姓名 年齡 性別 住址 班級 0 張三 7 男 NaN 一年級 1 李四 6 男 NaN 一年級 2 王芳 6 女 NaN 一年級 3 李明 8 男 NaN 二年級 4 劉敏 8 女 NaN 二年級 5 張強 7 男 NaN 二年級
修改列名為英文
df = df.rename(columns={'姓名': 'name', '年齡': 'age', '性別': 'sex', '住址': 'address', '班級': 'class'})
print(df)
name age sex address class 0 張三 7 男 NaN 一年級 1 李四 6 男 NaN 一年級 2 王芳 6 女 NaN 一年級 3 李明 8 男 NaN 二年級 4 劉敏 8 女 NaN 二年級 5 張強 7 男 NaN 二年級
將df保存為CSV、Excel文件
df.to_csv('../data/sheet合并.csv',index=False)
df.to_excel('../data/sheet合并.xls',index=True)
五、總結
可以發(fā)現(xiàn)Python讀寫Excel文件還是很方便的!
/python/blob/master/data/sheet%E5%90%88%E5%B9%B6.xls)
df.to_csv('../data/sheet合并.csv',index=False)
df.to_excel('../data/sheet合并.xls',index=True)
到此這篇關于教你用Python實現(xiàn)Excel表格處理的文章就介紹到這了,更多相關Python處理Excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python cookbook(數(shù)據(jù)結構與算法)讓字典保持有序的方法
這篇文章主要介紹了Python讓字典保持有序的方法,涉及Python基于collections模塊中的OrderedDict類實現(xiàn)控制字典順序的相關操作技巧,需要的朋友可以參考下2018-02-02
Python簡單實現(xiàn)網(wǎng)頁內(nèi)容抓取功能示例
這篇文章主要介紹了Python簡單實現(xiàn)網(wǎng)頁內(nèi)容抓取功能,結合實例形式分析了Python基于urllib模塊的網(wǎng)頁請求、內(nèi)容讀取等相關操作技巧,需要的朋友可以參考下2018-06-06
python數(shù)據(jù)分析近年比特幣價格漲幅趨勢分布
這篇文章主要為大家介紹了python分析近年來比特幣價格漲幅趨勢的數(shù)據(jù)分布,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-11-11
Python中列表遍歷使用range和enumerate的區(qū)別講解
這篇文章主要介紹了Python中列表遍歷使用range和enumerate的區(qū)別,在Python編程語言中,遍歷list有range和enumerate方法,本文結合示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12
Python統(tǒng)計單詞出現(xiàn)的次數(shù)
最近經(jīng)理交給我一項任務,統(tǒng)計一個文件中每個單詞出現(xiàn)的次數(shù),列出出現(xiàn)頻率最多的5個單詞。本文給大家?guī)砹藀ython 統(tǒng)計單詞次數(shù)的思路解析,需要的朋友參考下吧2018-04-04

