簡體   English   中英

為什么Python Pandas讀取一個excel文件的字符串作為datetime

[英]Why does Python Pandas read the string of an excel file as datetime

我有以下問題。

我有 Excel 個文件如下:

在此處輸入圖像描述

當我使用df = pd.read_excel(file,dtype=str)讀取文件時。 第一行變為2003-02-14 00:00:00而 rest 則按原樣顯示。

我如何防止pd.read_excel()將其值轉換為日期時間或其他內容?

謝謝!

正如@ddejohn 在評論中正確地說的那樣,您面臨的行為實際上來自 Excel,自動將數據轉換為日期。 因此 pandas 將不得不處理該數據作為日期,並在以后處理它以獲得正確的格式,就像你說你不能修改輸入 Excel 文件一樣。

這是一個簡短的腳本,可以使其按預期工作:

import pandas as pd

def rev(x: str) -> str:
    '''
    converts '2003-02-14 00:00:00' to '14.02.03'
    '''

    hours = '00:00:00'
    if not hours in x:
        return x
    y = x.split()[0]
    y = y.split('-')
    return '.'.join([i[-2:] for i in y[::-1]])

file = r'C:\your\folder\path\Classeur1.xlsx'
df = pd.read_excel(file, dtype=str)

df['column'] = df['column'].apply(rev)

df['column']替換為您的實際列名。 然后您在 dataframe 中獲得所需的格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM