【问题标题】:how to auto increment a dataframe column with time by specified time each and auto incrementing date with day?如何将数据框列随时间自动增加指定的时间,并自动增加日期与日期?
【发布时间】:2019-02-28 06:54:03
【问题描述】:

有一个带有值的df

             0     |   1
2019-02-22 13:40:58|  sun 
2019-02-22 13:40:58|  earth
2019-02-22 13:40:58|  mercury
2019-02-22 13:40:58|  moon
2019-02-22 13:40:58|  mars
2019-02-22 13:40:58|  jupyter

1.如何在每种情况下将时间自动增加一分钟

所需的输出 1。

            0      |   1
2019-02-22 13:41:58|  sun 
2019-02-22 13:42:58|  earth
2019-02-22 13:43:58|  mercury
2019-02-22 13:44:58|  moon
2019-02-22 13:45:58|  mars
2019-02-22 13:46:58|  jupyter

2.通过使用它我们可以在中间添加一天

df[0] = pd.to_datetime(df[0], unit='ms').dt.strftime('%Y-%m-%d %a %H:%M:%S')

结果

2019-02-08 Fri 12:19:06

如何增加这些也

输出 2(包括日期名称)

            0      |   1
2019-02-17 sun  13:41:58|  sun 
2019-02-18 mon  13:42:58|  earth
2019-02-19 tue  13:43:58|  mercury
2019-02-20 wed  13:44:58|  moon
2019-02-21 thur 13:45:58|  mars
2019-02-22 fri  13:46:58|  jupyter

【问题讨论】:

    标签: python python-3.x pandas datetime dataframe


    【解决方案1】:

    您可以转换递增/递减Seriesarrays to_timedelta和加减datetimes:

    df[0] = pd.to_datetime(df[0], unit='ms')
    

    如果需要为每个唯一的日期时间递增和递减分钟和天数:

    s1 = pd.to_timedelta(df.groupby(0).cumcount() + 1, unit='m')
    s2 = pd.to_timedelta(df.groupby(0).cumcount(ascending=False), unit='d')
    

    或者如果第一列中的所有日期时间都相同:

    s1 = pd.to_timedelta(np.arange(1, len(df) + 1), unit='m')
    s2 = pd.to_timedelta(np.arange(len(df)-1,-1, -1), unit='d')
    

    df[0] = (df[0] + s1 - s2).dt.strftime('%Y-%m-%d %a %H:%M:%S')
    print (df)
                             0        1
    0  2019-02-17 Sun 13:41:58      sun
    1  2019-02-18 Mon 13:42:58    earth
    2  2019-02-19 Tue 13:43:58  mercury
    3  2019-02-20 Wed 13:44:58     moon
    4  2019-02-21 Thu 13:45:58     mars
    5  2019-02-22 Fri 13:46:58  jupyter
    

    【讨论】:

    • 获取此不可兑换价值 2019-02-05 Tue 23:50:30,单位为“ms”
    • @hukkemaaru - 然后使用df[0] = pd.to_datetime(df[0], format='%Y-%m-%d %a %H:%M:%S')
    • 如果我只需要增加分钟而不是日期?
    • @hukkemaaru - 然后将 s2df[0] + s1 - s2 删除到 df[0] + s1
    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2011-03-15
    • 2016-11-09
    • 1970-01-01
    • 2021-07-24
    • 2013-10-29
    相关资源
    最近更新 更多