【问题标题】:Python pandas Can I calculate the delta of column values by the ID of another column in minute increments?Python pandas 我可以通过另一列的 ID 以分钟为增量计算列值的增量吗?
【发布时间】:2023-01-04 20:05:16
【问题描述】:

我有一个看起来像这样的 Csv 文件

Time Count Operation
10:01:00 2 Up
10:01:00 5 Down
10:01:00 1 Down
10:01:00 2 Up
10:01:00 1 Up
10:02:00 3 Down
10:02:00 2 Up
10:02:00 5 Down

我想通过操作列的 id 将每分钟的计数列的值相加,然后在同一分钟内减去彼此的上下总和,这应该给我这样的东西

Sum():

Time Count Operation
10:01:00 5 Up
10:01:00 6 Down
10:02:00 2 Up
10:02:00 8 Down

Diff():

Time Delta
10:01:00 1
10:02:00 6

为此,我尝试类似

def Delta_Volume():
    df = pd.read_csv(Ex_Csv, usecols=['Time','Count','Operation'], parse_dates=[0])
    df['Time'] = df['Time'].dt.floor("T", 0).dt.time
    df1 = df.groupby('Operation').sum('Count')
    df2 = df.groupby('Operation').diff('Count')
    #df['Delt_of_row'] = df.loc[1 : 3,['Count' , 'Operation']].sum(axis = 1)
    #df['Delt_of_row'] = df.loc[1 : 3,['Count' , 'Operation']].diff(axis = 1)
    print(df1)

但不幸的是,它并没有按照我需要的方式工作

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以从经典的 GroupBy.sum 开始,然后使用 MultiIndex 计算差异:

df2 = df.groupby(['Operation', 'Time']).sum()
print(df2)

out = df2.loc['Down']-df2.loc['Up']
print(out)

输出:

# groupby.sum
                    Count
Operation Time           
Down      10:01:00      6
          10:02:00      8
Up        10:01:00      5
          10:02:00      2

# difference
          Count
Time           
10:01:00      1
10:02:00      6

【讨论】:

  • 你再次用 mozway 公式解决了我的大部分问题
【解决方案2】:
def function1(dd:pd.DataFrame):
    return dd.Count.diff(-1).head(1)

df1.groupby(['Time','Operation'],as_index=False).sum()
    .groupby('Time').apply(function1).droplevel(1)

出去

          Count
Time           
10:01:00      1
10:02:00      6

【讨论】:

    猜你喜欢
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    • 2021-01-19
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多