创建timeseries存储箱和索引

2024-05-12 22:51:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我收集了一些实验数据,这些数据是以固定的时间间隔从大量的样本中收集的,数据框架是这样组织的:

Studynumber    Time    Concentration
1               20         80
1               40         60
1               60         40
2               15         95 
2               44         70
2               65         30

虽然时间间隔应该是固定的,但是数据在实际收集的时间上有一些变化。我想创建时间列的容器,计算一个“平均”浓度,然后比较每次每个研究编号的实际浓度和平均浓度之间的差异。你知道吗

为此,我创建了一个名为“roundtime”的列,然后使用groupby来计算平均值:

data['roundtime']=data['Time'].round(decimals=-1)
meanconc = data.groupby('roundtime')['Concentration'].mean()

这给出了一系列的平均浓度,以roundtime为指标。然后我想把它放回到主框架中,计算每个实际浓度和平均浓度之间的差值:

data['meanconcentration']=meanconc.loc[data['roundtime']].reset_index()['Concentration']

这适用于前60个左右的值,但是对于每个条目都返回NaN,我认为是因为数据索引比平均浓度索引长。你知道吗

一方面,这看起来像一个索引问题-同样,它可能是我只是接近这个错误的方式。所以我的问题是:a)这种方法行得通吗?b)有没有其他/更好的方法?欢迎各位指教!你知道吗


Tags: 数据方法框架data间隔time时间容器
2条回答

使用^{}groupby聚合中添加一列,这将创建一个Series,其索引与原始df对齐,以便您可以正确地重新分配它:

In [4]:
df['meanconcentration'] = df.groupby('roundtime')['Concentration'].transform('mean')
df

Out[4]:
   Studynumber  Time  Concentration  roundtime  meanconcentration
0            1    20             80         20               87.5
1            1    40             60         40               65.0
2            1    60             40         60               35.0
3            2    15             95         20               87.5
4            2    44             70         40               65.0
5            2    65             30         60               35.0

你在写什么

Then I want to get this back into the main frame to calculate the difference between each actual concentration and the mean concentration

Data Wrangling in Pandasgroupby-apply的文档中出现了一些非常类似的内容。请注意,您可以直接计算:

>>> data.groupby('roundtime').apply(
    lambda g: g.Concentration - g.Concentration.mean())
roundtime   
20         0   -7.5
           3    7.5
40         1   -5.0
           4    5.0
60         2    5.0
           5   -5.0
Name: Concentration, dtype: float64

请注意,您可以很容易地对此应用.reset_index(),如果需要,可以将其合并回原始数据帧,等等


另一种方法是计算平均值,然后直接将其合并:

pd.merge(
    data.groupby('roundtime').mean(),
    data,
    left_index=True,
    right_on='roundtime',
    how='right')

(请注意,这将为原始列创建列“Concentration\u X”for the mean, and'Concentration\u Y`)。你知道吗

相关问题 更多 >