【问题标题】:How to create a pandas DataFrame column based on two other columns that holds dates?如何基于包含日期的其他两个列创建 pandas DataFrame 列?
【发布时间】:2020-05-23 02:38:47
【问题描述】:

我有一个带有两个日期列(A 和 B)的 pandas 数据框,我想创建一个第三列 (C),其中包含使用 A 列和 B 列的日期使用月份和年份创建的日期。显然我会需要将日期更改为不存在的月份,就像我们尝试创建 2020 年 2 月 31 日一样,它需要将其更改为 2020 年 2 月 29 日。

例如

import pandas as pd
df = pd.DataFrame({'A': ['2020-02-21', '2020-03-21', '2020-03-21'], 
                   'B': ['2020-01-31', '2020-02-11', '2020-02-01']})
for c in df.columns:
    dfx[c] = pd.to_datetime(dfx[c])

然后我想创建一个新的列 C,它是一个新的日期时间:

年份 = df.A.dt.year

月 = df.A.dt.month

天 = df.B.dt.day

我不知道如何创建此列。你能帮忙吗?

【问题讨论】:

标签: python pandas


【解决方案1】:

这是使用 pandas 的时间序列功能的一种方法:

import pandas as pd

# your example data
df = pd.DataFrame({'A': ['2020-02-21', '2020-03-21', '2020-03-21'], 
                   'B': ['2020-01-31', '2020-02-11', '2020-02-01']})
for c in df.columns:
    # keep using the same dataframe here
    df[c] = pd.to_datetime(df[c])

# set back every date from A to the end of the previous month,
# then add the number of days from the date in B
df['C'] = df.A - pd.offsets.MonthEnd() + pd.TimedeltaIndex(df.B.dt.day, unit='D')

display(df)

结果:

             A           B           C
0   2020-02-21  2020-01-31  2020-03-02
1   2020-03-21  2020-02-11  2020-03-11
2   2020-03-21  2020-02-01  2020-03-01

正如您在第 0 行中看到的那样,它处理“2 月 31 日”的情况并不完全按照您的建议,但仍以合乎逻辑的方式。

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 2016-02-10
    • 2021-12-27
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多