【问题标题】:Python groupby ID and increment the associated columnPython groupby ID 并增加关联列
【发布时间】:2018-07-04 11:20:01
【问题描述】:

我在熊猫数据框中有以下数据。数据以 50khz 采样,因此每个 ID 组的“微秒”字段必须增加 50。

数据----ID----微秒

0.304 ----1 ---- 1530348553000
0.276 ----1 ----15303485530000
0.276 ----1 ----15303485530000
0.276 ----2 ----15303490090000
0.276 ----2 ----15303490090000
0.304 ----2 ----15303490090000
0.276 ----3 ----15303553530000
1.359 ----3 ----15303753680000
1.443 ----3 ----15303753680000

需要输出

数据----ID----微秒

0.304 ----1 ---- 1530348553000
0.276 ----1 ----15303485530050
0.276 ----1 ----15303485530100
0.276 ----2 ----15303490090000
0.276 ----2 ----15303490090050
0.304 ----2 ----15303490090100
0.276 ----3 ----15303553530000
1.359 ----3 ----15303753680050
1.443 ----3 ----15303753680100

代码

import numpy as np
from itertools import chain

lens = list(map(len, df['Data'].str.split('|')))
df['microsec'] = pd.DatetimeIndex ( df['DateTime'] ).astype ( np.int64 )// 10 ** 9

df['Data'] = df['Data'].str.replace(',','.')

res = pd.DataFrame({'ID': np.repeat(df['ID'], lens),
                    'microsec': np.repeat(df['microsec']*10000, lens),
                    'Data': list(chain.from_iterable(df['Data'].str.split('|')))    
                   })

res[['Data']] = res[['Data']].astype(float)
res.to_csv('samplefile.txt', index=False)

我尝试了什么

df_groups = res.groupby('MeasurementID')
for MeasurementID,microsec in df_groups:
     microsec = microsec*50
     print(microsec)

但我没有达到我想要的输出。请让我知道我哪里做错了。

【问题讨论】:

  • 看来需要groupby + cumsum,检查this
  • 请阅读help files。这个问题写得不好。
  • 您好 Nrithya,您能否通过提供一个实际问题来编辑您的问题:向我们解释您想要达到的结果是什么。谢谢。
  • @TomZych:我还在编辑过程中,我没有意识到它已经发布了。不过谢谢你:)

标签: python pandas


【解决方案1】:

我认为下面的代码应该可以工作。

def func(col,base):
    for i in range(len(col)):
        col.iloc[i]=col.iloc[i]+base
        base=base+50
    return col

df.groupby(['Data','ID'])['microsec'].transform(lambda x:func(x,0))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多