![](/img/trans.png)
[英]DataFrame contains a column of dates which are having these types: "'5-15-2019'" and 05152021.I want to extract pattern of it
[英]i want to convert 1-May-19 and 5/1/2019 to 1/5/2019 in my dataframe
我有2列日期格式:5/1/2019和1-May-19。 我希望他們在1/5/2019格式。
這里提到的代碼似乎沒有改變1列的格式,我需要將這兩列轉換為格式1/5/2019
df['billing_start_date'] = (pd.to_datetime(df['billing_start_date'], format='%Y/%m/%d').dt.strftime('%m/%d/%Y'))
使用帶有不同format
的to_datetime
的Series.dt.strftime
:
df = pd.DataFrame({"a":["5/1/2019"], "b":["1-May-19"]})
df['a'] = pd.to_datetime(df['a'], format='%m/%d/%Y').dt.strftime('%m/%d/%Y')
df['b'] = pd.to_datetime(df['b'], format='%d-%b-%y').dt.strftime('%m/%d/%Y')
print (df)
a b
0 05/01/2019 05/01/2019
# I guess you have two different columns with different dateformats as per the # question , please check the below answer.
from datetime import datetime
df=pd.DataFrame({'start_date':['5/1/2019','7/11/2019','3/10/2019'],
'end_date':['1-May-19','2-Mar-19','11-May-19']})
df
start_date end_date
0 5/1/2019 1-May-19
1 7/11/2019 2-Mar-19
2 3/10/2019 11-May-19
def try_parsing_date(text):
for fmt in ("%m/%d/%Y",'%d-%b-%y'):
try:
return datetime.strptime(text, fmt).strftime('%d/%m/%Y')
except ValueError:
pass
raise ValueError('no valid date format found')
df['new_start_date']=df['start_date'].apply(try_parsing_date)
df['new_end_date']=df['end_date'].apply(try_parsing_date)
df
start_date end_date new_start_date new_end_date
0 5/1/2019 1-May-19 01/05/2019 01/05/2019
1 7/11/2019 2-Mar-19 11/07/2019 02/03/2019
2 3/10/2019 11-May-19 10/03/2019 11/05/2019
你有正確的方法,但執行錯誤
我們的開始df:
df = pd.DataFrame({"col_1":["5/1/2019"], "col_2":["1-May-19"]})
col_1 col_2
5/1/2019 1-May-19
以下是如何通過簡單的解決方案實現此目的:
df["col_1"] = pd.to_datetime(df["col_1"])
df["col_2"] = pd.to_datetime(df["col_1"])
df["col_1"] = df["col_1"].dt.strftime('%d/%m/%Y')
df["col_2"] = df["col_2"].dt.strftime('%d/%m/%Y')
這使 :
col_1 col_2
01/05/2019 01/05/2019
或者用方法鏈接兩行
df["col_1"] = pd.to_datetime(df["col_1"]).dt.strftime('%d/%m/%Y')
df["col_2"] = pd.to_datetime(df["col_1"]).dt.strftime('%d/%m/%Y')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.