【问题标题】:how to reset a counter every new day using pandas and numpy?如何使用 pandas 和 numpy 每天重置一个计数器?
【发布时间】:2020-04-16 14:03:38
【问题描述】:

Excel 表中有 2 列(“input.xlsx”):“时间(分钟)”和“日期”。首先,我想将这些列转换为 numpy 数组,因为我想将这些值用于进一步使用。时间列增加了 15 分钟,我希望每隔 15 分钟计数器列值增加 1。此外,我希望该计数器值在每个新的一天重置。

期望的输出(控制台结果(不是 Xlsx 格式)):

Time(min)        Date       counter  
00:00        27-Aug-18      1
00:15        27-Aug-18      2
00:30        27-Aug-18      3
00:45        27-Aug-18      4
01:00        27-Aug-18      5
01:15        27-Aug-18      6
.
.
.
23:45        27-Aug-18     96
00:00        28-Aug-18     1
00:15        28-Aug-18     2

【问题讨论】:

    标签: python pandas python-2.7 numpy


    【解决方案1】:
    df['counter'] = 1
    df['counter'] = df[['counter','Date']].groupby('Date').transform(lambda x: x.cumsum())
    

    编辑:输出为 numpy 数组

    这两个 numpy 数组将是 datacounter

    • data - 包含 TimeDate
    • counter - 包含计数器列
    df = pd.read_excel('input.xlsx', header=0)
    
    # Data as it is (DateTime objects and Timestamp objects)
    data = df.to_numpy() 
    # Or convert all entries to strings
    data = df.astype(str).to_numpy()
    
    df['counter'] = 1
    counter = df[['counter','Date']].groupby('Date').transform(lambda x: x.cumsum()).to_numpy()
    

    【讨论】:

    • 实际上我需要 numpy 数组格式的值,我已经在我的问题中提到过。
    • 什么是 numpy 数组格式?你想要一个来自 df 的 numpy 数组吗?如果是这样,只需使用df.to_numpy()。但是如果你想在 numpy 中进行完整的计算,不确定你是否可以像在 Pandas 中一样优雅地实现这一点。
    • 评论:虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。我建议您查看 SO 的 official How to Answer article 以及来自 Jon Skeet 的综合 blog post。现在我将您的答案标记为删除。
    • 我需要将前两列“时间(分钟)”和“日期”的值存储到 numpy 数组中,然后计算“计数器”的值并将这些“计数器”数组的值显示在控制台(不是 excel 格式)。
    • @nipunvats,让我直说吧。所以你想要两个 numpy 数组 1) 包含时间和日期 2) 包含计数器。只要最后这两个是numpy数组,就可以用上面的计算吗?
    猜你喜欢
    • 1970-01-01
    • 2014-12-14
    • 2022-01-09
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2018-08-04
    相关资源
    最近更新 更多