计算行条目以调整不同的列熊猫

时间:2019-01-14 19:29:40

标签: python pandas mean

我试图通过计算不同列中行条目的频率来更新列条目。这是我的数据样本。实际数据包括10k个样本,每个样本的长度为220。(220秒)。

d = {'ID':['a12', 'a12','a12','a12','a12', 'a12', 'a12','a12','v55','v55','v55','v55','v55','v55','v55', 'v55'], 
     'Exp_A':[0.012,0.154,0.257,0.665,1.072,1.514,1.871,2.144, 0.467, 0.812,1.59,2.151,2.68,3.013,3.514,4.015], 
     'freq':['00:00:00', '00:00:01', '00:00:02', '00:00:03', '00:00:04',
                '00:00:05', '00:00:06', '00:00:07','00:00:00', '00:00:01', '00:00:02', '00:00:03', '00:00:04',
                '00:00:05', '00:00:06', '00:00:07'],
     'A_Bullseye':[0,0,0,0,1,0,1,0, 0,0,1,0,0,0,1,0], 'A_Bull_Total':[0,0,0,0,0,1,1,2,0,0,0,1,1,1,1,2], 'A_Shot':[0,1,1,1,0,1,0,0, 1,1,0,1,0,1,0,0]}
df = pd.DataFrame(data=d)

每秒只能注册“靶心”或“射击”。

计数1:每个df.A_Shot == 1的第一个df.A_Bullseye == 1之前的ID的数量为3 & 2 for ID=a12 and ID=v55 resp

Count2:从count1末尾到第二个df.A_Shot == 1的{​​{1}}数,df.A_Bullseye == 11的{​​{1}}

df[df.ID=='a12']中的2 for df[df.ID=='v55']i。这里的count(i)df.groupby(by='ID')[A_Bull_Total].max()

因此,如果我可以计算每个i的平均计数,那么我将能够使用上述计数的平均值来调整df.Exp_A的值。

i

理想情况下,我想为每个i(Bullseye)提供类似的东西,需要多少次射击以及花费多少秒。

1 个答案:

答案 0 :(得分:3)

使用Bullseye在每个ID中创建.cumsum的分组密钥,然后您可以找到多少个镜头以及两次牛车之间经过了多少时间。

import pandas as pd

df['freq'] = pd.to_timedelta(df.freq, unit='s')
df['Bullseye'] = df.groupby('ID').A_Bullseye.cumsum()+1

# Chop off any shots after the final bullseye
m = df.Bullseye <= df.groupby('ID').A_Bullseye.transform(lambda x: x.cumsum().max())

df[m].groupby(['ID', 'Bullseye']).agg({'A_Shot': 'sum', 
                                       'freq': lambda x: x.max()-x.min()})

输出:

              A_Shot     freq
ID  Bullseye                 
a12 1              3 00:00:03
    2              1 00:00:01
v55 1              2 00:00:01
    2              2 00:00:03

编辑:

给出您的评论,这就是我将如何进行。我们将要进入​​.shift靶心列,因此我们要在靶心的之后行增加计数器,而不是在靶心处增加计数器。我们将修改A_Shot,以便也将Bullseyes视为一个镜头。

df['freq'] = pd.to_timedelta(df.freq, unit='s')
df['Bullseye'] = df.groupby('ID').A_Bullseye.apply(lambda x: x.shift().cumsum().fillna(0)+1)

# Also consider Bullseye's as a shot:
df.loc[df.A_Bullseye == 1, 'A_Shot'] = 1

# Chop off any shots after the final bullseye
m = df.Bullseye <= df.groupby('ID').A_Bullseye.transform(lambda x: x.cumsum().max())

df1 = (df[m].groupby(['ID', 'Bullseye'])
            .agg({'A_Shot': 'sum', 
                  'freq': lambda x: (x.max()-x.min()).total_seconds()}))

输出:df1

              A_Shot  freq
ID  Bullseye              
a12 1.0            4   4.0
    2.0            2   1.0
v55 1.0            3   2.0
    2.0            3   3.0

由于freq是整数秒,因此您可以轻松进行除法:

df1.A_Shot / df1.freq

#ID   Bullseye
#a12  1.0         1.0
#     2.0         2.0
#v55  1.0         1.5
#     2.0         1.0
#dtype: float64