我有一個df我想將某些列型別更改為datefrom datetime:
field category 2022-01-10 00:00:00 2022-01-17 00:00:00 2022-01-24 00:00:00
A 10 500 700 500
B 15 60 70 50
我正在努力實作這一目標:
field category 2022-01-10 2022-01-17 2022-01-24
A 10 500 700 500
B 15 60 70 50
因為在與其他連接期間df,列型別從2021-11-19變為2021-11-19 00:00:00。
從這個答案我試過::
df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : pd.to_datetime('2022-06-20 00:00:00')].columns =
pd.to_datetime(df.loc[:,pd.to_datetime('2022-01-10 00:00:00') :
pd.to_datetime('2022-06-20 00:00:00')].columns)
.strftime('%Y-%m-%d')
但這并沒有改變我無法理解的列的型別,因為
pd.to_datetime(df.loc[:,pd.to_datetime('2022-01-10 00:00:00') : pd.to_datetime('2022-06-20 00:00:00')].columns).strftime('%Y-%m-%d')
回傳:
Index(['2022-01-10', '2022-01-17', '2022-01-24')]
uj5u.com熱心網友回復:
在您的列索引中,您將字串(“欄位”和“類別”)和時間戳(其他列)混合在一起,因此您的列索引Index不是DatetimeIndex.
>>> df.columns
Index([ 'field', 'category', 2022-01-10 00:00:00,
2022-01-17 00:00:00, 2022-01-24 00:00:00],
dtype='object')
>>> [type(c) for c in df.columns]
[str,
str,
pandas._libs.tslibs.timestamps.Timestamp,
pandas._libs.tslibs.timestamps.Timestamp,
pandas._libs.tslibs.timestamps.Timestamp]
的默認字串表示Timestamp是YYYY-mm-dd HH:MM:SS同時的每個值的默認表示DatetimeIndex可以是YYYY-mm-dd只(如果可能)。
要獲取日期格式,您必須將您Timestamp的字串轉換為字串。
uj5u.com熱心網友回復:
鑒于此,特定的列型別是日期時間。您可以使用 pandas 的 dt.date 僅保留日期。請看下面的例子。
dates_only = df["datetime"].dt.date
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409557.html
標籤:
上一篇:如何在python中將這種格式'2017-12-0223:55:66.333 01:00'的str轉換為datetime?
