pandas 將excell轉爲csv,並且替換掉excell裏面的換行符,處理完日期
業務需求:公司從外部獲取了一份excell文件,需要把文件放到hive裏面,excell裏面有不符合要求的日期格式,並且字段裏面包含換行符,hive識別後,會造成字段串位,所以需要把excell的日期和換行符處理完成之後,轉成csv,然後推到集羣
- 將excell轉成csv
def excell_to_csv(excell_file_path, date_time_index=[], skiprows=0, format="%Y/%m/%d %H:%M:%S"):
"""
:param excell_file_path: excell文件路徑,處理完成之後會在excell文件的路徑下,生成以asv結尾的csv文件
:param date_time_index: 需要處理的時間日期所在的列
:param skiprows: 從第幾行開始處理,默認不帶字段名,如果有字段名,這skiprows=1,自動跳過第一行
:param format: excell文件裏面日期的格式
:return:
"""
# headre=None,讀取excell文件,認爲excell文件裏面第一行不是字段名
excell_dataframe = pd.read_excel(excell_file_path, header=None, skiprows=skiprows)
print(excell_dataframe)
for index in date_time_index:
# 遇到日期中有不是標準格式的日期,兩種解決辦法:1.errors="coerce",2.infer_datetime_format=True 兩種方法都會把非標準日期,轉換爲空
excell_dataframe[index] = pd.to_datetime(excell_dataframe[index], format=format, errors="coerce")
# excell_dataframe[index] = pd.to_datetime(excell_dataframe[index], infer_datetime_format=True)
# 利用正則,把每個字段裏面的換行調換掉
excell_dataframe = excell_dataframe.replace(to_replace=r"\n", value="", regex=True).replace(to_replace=r"\r", value="", regex=True).replace(to_replace=r"\r\n", value="", regex=True)
# 把讀取的dataframe數據生成csv,index=False,不要行索引,header=None不要列名,sep="\001"以ascall1作爲csv文件分隔符(此時在linux下,vi打開asv文件可以看到分隔符),分隔符可以自定義
excell_dataframe.to_csv("{}".format(excell_file_path.replace(".xlsx",".asv").replace(".xls", ".asv")), index=False, header=None, encoding='utf-8', sep='\001')
if __name__ == '__main__':
excell_to_csv('cc_complaint.xls', date_time_index=[1, 2], skiprows=1)
- cc_complaint.xls 文件,沒有找到上傳附件的方法,只能粘貼xls文件,注意每一行數據都會和下一行數據隔一個空行,有的字段裏面有換行,所以一條數據可能在多行
案例編號 案例日期 消費時間 備註
1808118720 2018/8/14 18:14:19 2018/8/14 "2018/08/14 18:17:36 MCD009:
感謝反饋,留4009200205熱線,故此案關閉。"
1808121500 2018/8/16 18:01:20 2018/8/16 18:01 "2018/08/16 18:09:30 MCD080:
已安撫顧客 告知會盡快處理
2018/08/16 18:20:46 MCD001:
聯繫餐廳孫經理,告知經理顧客來電訴求,經理了解。"
1808121498 2018/8/16 17:58:30 2018/8/16 17:58:30 "2018/08/16 18:05:29 MCD304:
在線記錄覈實反饋"
1808121493 2018/8/16 17:56:36 222222
1808121486 2018/8/16 17:52:10 2018/8/16 17:52:10
1808121485 2018/8/16 17:51:58 2018/8/16 17:51:58
1808121484 2018/8/16 17:51:54 2018/8/16 17:51:54
- cc_complaint.xls 文件圖片如圖