我正在決議我的資料集的日期,但遇到了很多,ParserError因為時間通常格式錯誤。我決定跳過時間,只關注年、月、日
這些是我的日期變體:
| 開始日期 |
| --- |
| 2022 年 3 月 23 日 6:00 |
| 2022 年 3 月 23 日 7:0 |
| 2022 年 3 月 23 日 7: |
| 2022 年 3 月 23 日 7 |
目前,只有第一個日期/行可用于決議資料。我目前跳過了其他行,但是我還想通過僅排除時間來包括它們。
for date in df_en['Startdate']:
try:
parse(date).date()
except Exception:
pass
什么是仍然決議其他日期而不必費心時間的正確方法?
我試圖將時間轉換為有效的小時格式。usingpd.to_datetime不起作用,因為時間格式是 strmarch而不是 number 3。當手動更改為 3 時,它仍然給出錯誤ValueError: unconverted data remains: :00。因此,幾個小時都沒有相關性,我只想跳過它。
來源:https ://serveanswer.com/questions/converting-to-datetime-parsererror-unknown-string-format-2022-02-17-7
dates = ['December 1, 2021 6:00', 'March 23, 2022 6']
for date in dates:
date.replace(' (\d{1})', ' 0\\1')
pd.to_datetime(date, format='%m %d, %Y %H')
print(date)
最終目標:
| 年份 | 月 | 天 |
| --- | --- | --- |
| 2022 | 三月 | 23 |
| 2022 | 三月 | 三月 |
uj5u.com熱心網友回復:
如果您只需要年/月/日列,則實際上無需決議為日期時間。只需通過拆分和重新排列來處理字串;前任:
import pandas as pd
df = pd.DataFrame({'Startdate': ['December 1, 2021 6:00', 'March 23, 2022 6']})
parts = df['Startdate'].str.split('\ |, ')
df['year'], df['month'], df['day'] = parts.str[2], parts.str[0], parts.str[1]
print(df)
# Startdate year month day
# 0 December 1, 2021 6:00 2021 December 1
# 1 March 23, 2022 6 2022 March 23
uj5u.com熱心網友回復:
我想你可以轉儲小時部分
dates = ['March 23, 2022 6:00', 'March 23, 2022 7:0', 'March 23, 2022 7:', 'March 23, 2022 7']
pd.to_datetime([' '.join(x.split(' ')[:-1]) for x in dates])
DatetimeIndex(['2022-03-23', '2022-03-23', '2022-03-23', '2022-03-23'], dtype='datetime64[ns]', freq=None)
之后,您可以df['date'].dt.year提取年、月、日
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452712.html
