Python Pandas – 以stringforms读取date列

我有一个Excel文件中的一些数据,我读它使用pandasread_excel方法。 不过,我想读取所有列中的所有数据作为string,包括date列。

问题是我想离开date列作为string的原始格式。 例如,我在Excel中有'31 .01.2017',它被格式化为date,我想在我的数据框中有'31 .01.2017'。

我认为使用dtype = str的read_excel的dytpes参数是正确的方法。 但pandas然后读取date时间的date列,然后将其转换为string。 所以最后我总是在我的数据框中有“2017-01-31 00:00:00”。

有没有办法做到这一点?

正如您试图保持date列在初始types,下面的代码可能会帮助你。 在第一行中,我们向variables“cols”插入除date列以外的所有列,然后在以下两行中我们只更改其余列的types:

cols=[i for i in df.columns if i not in ["Date_column"]] for col in cols: df[col]=df[col].astype('category') 

希望能帮助到你! 🙂

 df['date_column'] = df['date_column'].dt.strftime('%d.%m.%Y')