【问题标题】:Add Time column by adding timedelata in pandas通过在 pandas 中添加 timedelta 来添加时间列
【发布时间】:2018-06-11 21:35:05
【问题描述】:

我有一个熊猫数据框 df:

id    value     mins
1      a         12.4
2      u         14.2
3      i         16.2
3      g         17.0

我有一个 datetime.datetime 变量:

current_time = datetime.datetime(2018, 1, 2, 14, 0, 34, 628481)

我想在我的 df 'total_time' 中添加新列 这样对于每一行,它都会在 current_time 中添加增量值 mins。

id    value     mins        total_time
1      a         12.4   current_time+timedelta(minutes = 12.4)
2      u         14.2            and
3      i         16.2            so
3      g         17.0            on... for every row

我试过了:

df['total_time' = current_time+timedelta(minutes = df['mins'].item())

但我得到了一个错误:

can only convert an array of size 1 to a Python scalar

还有其他方法吗?

我正在使用 datetime.datetime 包

【问题讨论】:

    标签: pandas


    【解决方案1】:

    我认为您需要 to_timedeltaT 几分钟:

    df['total_time'] = current_time + pd.to_timedelta(df['mins'], unit='T')
    print (df)
       id value  mins                 total_time
    0   1     a  12.4 2018-01-02 14:12:58.628481
    1   2     u  14.2 2018-01-02 14:14:46.628481
    2   3     i  16.2 2018-01-02 14:16:46.628481
    3   3     g  17.0 2018-01-02 14:17:34.628481
    

    详情:

    print (pd.to_timedelta(df['mins'], unit='T'))
    0   00:12:24
    1   00:14:12
    2   00:16:12
    3   00:17:00
    Name: mins, dtype: timedelta64[ns]
    

    【讨论】:

    • 哇!好的!另外,如果我必须再添加一列作为timestamp,我可以这样做吗 - `df['timestamp'] = int(datetime.timestamp(df['total_time'])) `?
    • 我试过用这个:`df['timestamp'] = int(datetime.timestamp(pd.to_datetime(df['total_time']))) `但是得到了错误:descriptor 'timestamp' requires a 'datetime.datetime' object but received a 'Series'跨度>
    • 不确定是否理解,什么是新栏目?是日期时间吗?你能解释更多吗?或者需要20180102141258628481 之类的东西?
    • 您需要从日期时间创建整数吗?
    • 好吧,我看到一个问题:我的current_time = datetime.datetime 的数据类型,但是我的`df = pandas.tslib.Timestamp` 中的total_time 类型我不能保持与日期时间相同的数据类型吗.datetime?
    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 2019-07-08
    • 2014-04-28
    • 2018-03-04
    • 2015-03-01
    • 2019-05-31
    相关资源
    最近更新 更多