pandas快速處理Excel,替換Nan,轉字典
pandas讀取Excel
import pandas as pd
# 參數1:文件路徑,參數2:sheet名
pf = pd.read_excel(path, sheet_name='sheet1')
刪除指定列
# 通過列名刪除指定列
pf.drop(['序號', '替代', '簽名'], axis=1, inplace=True)
替換列名
# 舊列名 新列名對照
columns_map = {
'列名1': 'newname_1',
'列名2': 'newname_2',
'列名3': 'newname_3',
'列名4': 'newname_4',
'列名5': 'newname_5',
# 沒有列名的情況
'Unnamed: 10': 'newname_6',
}
new_fields = list(columns_map.values())
pf.rename(columns=columns_map, inplace=True)
pf = pf[new_fields]
替換 Nan
通常使用
pf.fillna('新值')
替換表格中的空值,(Nan)。
但是,你可能會發現 fillna() 會有不好使的時候,記得加上 inplace=True
# 加上 inplace=True 表示修改原對象
pf.fillna('新值', inplace=True)
官方對 inplace 的解釋
inplace : boolean, default False
If True, fill in place. Note: this will modify any other views on this object, (e.g. a no-copy slice for a column in a DataFrame).
全列輸出不隱藏
- 你可能會發現,輸出表格的時候會出現隱藏中間列的情況,只輸出首列和尾列,中間用 … 替代。
加上下面的這句話,再打印的話,就會全列打印。
pd.set_option('display.max_columns', None)
print(pf)
將Excel轉換爲字典
pf_dict = pf.to_dict(orient='records')
全部代碼
import pandas as pd
pf = pd.read_excel(path, sheet_name='sheet1')
columns_map = {
'列名1': 'newname_1',
'列名2': 'newname_2',
'列名3': 'newname_3',
'列名4': 'newname_4',
'列名5': 'newname_5',
# 沒有列名的情況
'Unnamed: 10': 'newname_6',
}
new_fields = list(columns_map.values())
pf.drop(['序號', '替代', '簽名'], axis=1, inplace=True)
pf.rename(columns=columns_map, inplace=True)
pf = pf[new_fields]
pf.fillna('Unknown', inplace=True)
# pd.set_option('display.max_columns', None)
# print(smt)
pf_dict = pf.to_dict(orient='records')