【问题标题】:How to add date automatically based on the other column in python?如何根据python中的另一列自动添加日期?
【发布时间】:2021-06-06 07:12:02
【问题描述】:

我对 Datetime 和 pandas 很陌生。所以,我创建了一个代码,它为一列生成新数据(额外的行),而我的索引是日期。现在根据在列中创建的新行,日期也应该根据上述自动添加。有什么办法吗?

我的意见:

df=
            column1
2020-12-22    1
2020-12-23    2
2020-12-24    3

在我运行的代码在 column1 中获取更多数据之后,输出如下:

            column1
2020-12-22    1
2020-12-23    2
2020-12-24    3
0             4
1             5
3             6
4             7

预期输出:

    column1
2020-12-22    1
2020-12-23    2
2020-12-24    3
2020-12-25    4
2020-12-26    5
2020-12-27    6
2020-12-28    7

【问题讨论】:

    标签: python pandas datetime indexing dataset


    【解决方案1】:

    您可以通过 to_datetime 原始 DatetimeIndex 的最大日期时间创建 DatetimeIndex

    max1 = df.index.max()
    df1.index = pd.to_datetime(df1.index + 1, origin=max1, unit='D')
    

    【讨论】:

    • 我收到一个错误类型错误:不再支持带时间戳的整数和整数数组的加法/减法。不要加/减n,而是使用n * obj.freq
    • @sirisha - df1 没有DatetimeIndex,它有RangeIndex (0,1,2,3)
    • @sirisha - 和dfDatetimeIndex
    猜你喜欢
    • 2021-06-06
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2022-07-12
    相关资源
    最近更新 更多