【问题标题】:pandas, calculate diffrential, efficientlypandas,计算差异,高效
【发布时间】:2015-01-29 19:58:55
【问题描述】:

考虑每个患者的测量数据框和时间戳

patient     |  timestamp  |  x
A           |  2014-10-10 |  5.7
A           |  2014-10-11 |  6.3
B           |  2014-10-11 |  6.1
B           |  2014-10-10 |  4.1

我的目标是计算d,连续计算x 和最近一次测量中的x 之间的差异。

按照here的建议,这是我使用的代码

df.sort("timestamp", inplace=True)
df['d'] = df.groupby('patient')['x'].transform(pd.Series.diff).fillna(0)

但是,当尝试在具有多个测量值的数据帧上运行此代码时

patient     |  timestamp  |  x_1  |  ...  |  x_n

使用简单的循环:

df.sort("timestamp", inplace=True)
g=df.groupby('patient')
for x in df.columns:
    if x.find('x')>=0:
       df[x.replace('x','d')] = g[x].transform(pd.Series.diff).fillna(0)

代码运行很慢,

是否有更有效的方法来计算差异向量并将其连接到测量向量?

【问题讨论】:

    标签: python pandas time-series


    【解决方案1】:

    groupby 可能是一项昂贵的操作,并且您在循环中多次执行相同的操作。如果可能,尽量使用更少的groupbys 进行所有计算:

    cols = [col in df where col[0] = 'x']
    res = df.groupby('patient')[cols].diff().fillna(0)
    

    要连接,先重命名再加入:

    res = res.rename(columns=(lambda col: 'd'+col[1:]))
    df = df.join(res, how='outer')
    

    根据 pandas 和 numpy 的经验,如果您使用循环,您可能做错了什么。或者至少以次优方式。

    【讨论】:

    • 感谢@ari,我确实需要将结果连接到新列(例如以d 开头)
    猜你喜欢
    • 2021-04-03
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 2020-04-11
    • 2016-06-14
    • 2017-04-08
    相关资源
    最近更新 更多