gpt4 book ai didi

python Pandas : split and change the date format(one with eg:(aug 2018 - nov 2018)) and other with only one?

转载 作者:行者123 更新时间:2023-11-28 22:12:51 24 4
gpt4 key购买 nike

拆分日期2018 年 8 月 --> 01-08-2018 ??

这是我的示例输入

id      year_pass
1 Aug 2018 - Nov 2018
2 Jul 2017

这是我的示例输入 2

id      year_pass
1 Jul 2018
2 Aug 2017 - Nov 2018

我做了什么,我可以将日期拆分为例如:(2018 年 8 月 - 2018 年 11 月)

# splitting the date column on the '-'
year_start, year_end = df['year_pass'].str.split('-')
df.drop('year_pass', axis=1, inplace=True)

# assigning the split values to columns
df['year_start'] = year_start
df['year_end'] = year_end

# converting to datetime objects
df['year_start'] = pd.to_datetime(df['year_start'])
df['year_end'] = pd.to_datetime(df['year_end'])

但不知道如何为两者做到这一点

输出应该是:

id      year_start    year_end
1 01-08-2018 01-11-2018
2 01-07-2018

最佳答案

这是一种使用 dt.strftime("%d-%m-%Y") 的方法。

例如:

import pandas as pd

df = pd.DataFrame({"year_pass": ["Aug 2018 - Nov 2018", "Jul 2017"]})
df[["year_start", 'year_end']] = df["year_pass"].str.split(" - ", expand=True)
df["year_start"] = pd.to_datetime(df['year_start']).dt.strftime("%d-%m-%Y")
df["year_end"] = pd.to_datetime(df['year_end']).dt.strftime("%d-%m-%Y")
df.drop('year_pass', axis=1, inplace=True)

print(df)

输出:

   year_start    year_end
0 01-08-2018 01-11-2018
1 01-07-2017 NaT

根据评论编辑:

import pandas as pd

def replaceInitialSpace(val):
if val.startswith(" "):
return " - "+val.strip()
return val

df = pd.DataFrame({"year_pass": [" Jul 2018", "Aug 2018 - Nov 2018", "Jul 2017 "]})
df["year_pass"] = df["year_pass"].apply(replaceInitialSpace)
df[["year_start", 'year_end']] = df["year_pass"].str.split(" - ", expand=True)
df["year_start"] = pd.to_datetime(df['year_start']).dt.strftime("%d-%m-%Y")
df["year_end"] = pd.to_datetime(df['year_end']).dt.strftime("%d-%m-%Y")
df.drop('year_pass', axis=1, inplace=True)

print(df)

输出:

   year_start    year_end
0 NaT 01-07-2018
1 01-08-2018 01-11-2018
2 01-07-2017 NaT

关于 python Pandas : split and change the date format(one with eg:(aug 2018 - nov 2018)) and other with only one?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54456920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com