繁体   English   中英

如何将日期的特定格式转换为 Python Pandas 中有用且可读的日期格式?

[英]How to convert specific format of date to useful and readable format of date in Python Pandas?

我在 Pandas 中有 DataFrame,如下所示:

数据类型:

  • ID - 数字

  • 假期 - object

  • 年 - object

    ID 假期
    111 1 麦粒肿 2022年
    222 20 奎 2022年
    333 3月8日 2022年
    ... ... ...
  • 麦粒肿 - 一月

  • 奎 - 四月

  • 三月至三月

我需要转换上表以获得完整且有用的日期(字符串格式)。

所以,我需要像下面这样的东西:

ID  | HOLIDAY     | YEAR
----|-------------|-------
111 | 01-01-2022  | 2022
222 | 20-02-2022  | 2022
333 | 08-03-2022  | 2022
... | ...         | ...

我怎样才能在 Python Pandas 中做到这一点?

我用了这样的想法:

df['HOLIDAY'] = pd.to_datetime(df['HOLIDAY'] +" "+ df['YEAR'] , format='%d %b %Y')
df['HOLIDAY'] = df['HOLIDAY'].dt.strftime('%d-%m-%Y')

但它会产生如下错误: ValueError: time data '1 sty 2022' does not match format '%d %b %Y' (match)

你好,你可以使用这个:

d={'sty':'-1','kwi':'-4','mar':'-3'} #creat dict 

a=df.HOLIDAY.tolist() # creat list of original holiday
for i in range(len(df)):
    for word, replacement in d.items():
        a[i] = a[i].replace(word, replacement)# creat a loop that replace the mount by her number
        a[i] = a[i].replace(" ", "")# delete the space ex '1 sty' -> '1sty'
df.HOLIDAY=a
l=[]
for i in range(len(df)):
    l.append(str(df.HOLIDAY[i])+'-'+str(df.YEAR[i]))#loop that concatenat year and holiday

df.HOLIDAY=l# replace holiday in df by new values

df.HOLIDAY=pd.to_datetime(df.HOLIDAY, format="%d-%m-%Y")#transform holiday from str to datetime 

尝试:

df["HOLIDAY"] = df["HOLIDAY"].apply(
    lambda x: x.replace("sty", "January")
    .replace("kwi", "April")
    .replace("mar", "March")
)

df["HOLIDAY"] = pd.to_datetime(
    df["HOLIDAY"] + " " + df["YEAR"].astype(str)
).dt.strftime("%d-%m-%Y")

print(df)

印刷:

    ID     HOLIDAY  YEAR
0  111  01-01-2022  2022
1  222  20-04-2022  2022
2  333  08-03-2022  2022

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM