我有一個名為“result”的資料框,其中包含一個名為“Action”的列。此列包含許多字串,其中一些是日期。我試圖將包含日期的字串轉換為日期時間,忽略不包含日期的行,因為它們會出錯。
通常我會使用 pd.to_datetime(column =, format =, errors = 'ignore') 但在這種情況下,它不會轉換任何東西。
但是,當我更改錯誤 = 'coerce' 時,它確實會轉換日期,但當然會將其他所有內容都轉換為 NaN。我想使用忽略,因為其他行中仍然有有價值的資料。
result["Action"] = pd.to_datetime(result["Action"], format = '%A %B %d %Y', errors = 'ignore')

result["Action"] = pd.to_datetime(result["Action"], format = '%A %B %d %Y', errors = 'coerce')

uj5u.com熱心網友回復:
如果errors設定為ignore,則無效決議將回傳輸入。所以在你的情況下,輸入是result["Action"](整列)。
這個問題的解決方案是應用pd.to_datetime與橫行errors='ignore'。通過這樣做,如果該行不跟在format.
>>> import pandas as pd
>>>
>>> df = pd.DataFrame({'Action': ['Tuesday November 30 2021', 'Appointment time clicked']})
>>> df
Action
0 Tuesday November 30 2021
1 Appointment time clicked
>>>
>>> def custom(action):
... date_time = pd.to_datetime(action, format='%A %B %d %Y', errors='ignore')
... return date_time
...
>>> df.Action = df.Action.apply(custom)
>>> df
Action
0 2021-11-30 00:00:00
1 Appointment time clicked
uj5u.com熱心網友回復:
我能想到的一種解決方法是在需要時重新決議 DF
for d in result['Action']:
try:
res = pd.to_datetime(d, format = '%A %B %d %Y')
print(res)
except:
res = pd.to_datetime(d, format = '%A %B %d %Y', errors='ignore')
print(res)
uj5u.com熱心網友回復:
您可以執行以下操作:
tmp = pd.to_datetime(result["Action"], format='%A %B %d %Y', errors='coerce')
result.Action = result.Action.where(tmp.isna(), tmp.dt.date)
結果為
result =
Action
0 Tuesday November 30 2021
1 Appointment time clicked:
2 Appointment date clicked:
3 Tuesday November 30 2021
4 Appointment time clicked:
5 Tuesday November 30 2021
6 Tuesday November 30 2021
是
Action
0 2021-11-30
1 Appointment time clicked:
2 Appointment date clicked:
3 2021-11-30
4 Appointment time clicked:
5 2021-11-30
6 2021-11-30
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370823.html
上一篇:PythonPandas:附加列值,基于另一個相同的列值
下一篇:使用重復的重復值創建資料框
