【问题标题】:How to create a new data frame with the sum of the values of a column every n seconds in Python如何在Python中每n秒创建一个包含列值总和的新数据框
【发布时间】:2022-01-13 13:35:38
【问题描述】:

我需要每 0.1 秒创建一个新的 DataFrame,其中包含 AA 列的值的总和。 有什么功能可以轻松做到这一点吗?

Time AA

0.003 362
0.02  152
0.1   65
0.15  63
0.2   58
0.26  567
0.3   45
0.32  45
0.3   69 
...

预期输出:

time    sum
0-0.1   514
0.1-0.2 128
0.2-0.3 1147
...

【问题讨论】:

    标签: python pandas dataframe time sum


    【解决方案1】:

    这样的事情会起作用:

    import numpy as np
    import pandas as pd
    
    
    df["rounded_down"] = df["Time"].apply(lambda x: np.floor(x * 10) / 10)
    df["rounded_up"] = df["Time"].apply(lambda x: np.ceil(x * 10) / 10)
    # Assuming values get grouped upward (so .3 is in .3-.4,
    # you can change this by switching to subtracting from rounded_down)
    df.loc[df["rounded_down"] == df["rounded_up"], "rounded_up"] += 0.1
    df["time"] = df.apply(
        lambda x: str(round(x["rounded_down"], 1)) + "-" + str(round(x["rounded_up"], 1)), 
        axis=1)
    # Calculate result
    result = df.groupby("time")["AA"].sum().reset_index()
    

    【讨论】:

    • 太棒了,谢谢!
    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    相关资源
    最近更新 更多