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

标签 python pandas

分割日期,例如2018 年 8 月 --> 2018 年 1 月 8 日 ??

这是我的示例输入

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/

相关文章:

python - 将 groupby 与多个索引列或索引一起使用时

python - 具有最小值、最大值、平均值和标准差的箱线图

python - 如何计算分组 df 的差异?

python - 将纯文本标题和图像导出到 Excel

python - 如何使用 Pandas (Python) 报告用户-项目交互

python - 将行视为外部定义类的实例吗?

python - 从 (row,col,values) 的元组列表构造 pandas DataFrame

python - 尝试在Python中减去两个日期并在几小时内(大于24小时时间段)得到结果

python - 静态媒体无法在 Django 中加载

python - time.sleep() 时的交互?