python-3.x - 在 pandas 数据框中的行之间添加随机数据

标签 python-3.x pandas

我有一个像这样的 pandas 数据框。其中包含 timestampidfoobartimestamp 数据大约每 10 分钟一次。

timestamp            id  foo  bar
2019-04-14 00:00:10  1   0.10 0.05
2019-04-14 00:10:02  1   0.30 0.10
2019-04-14 00:00:00  2   0.10 0.05
2019-04-14 00:10:00  2   0.30 0.10

对于每个id,我想创建5个额外的,其中timestamp在连续的之间平均分割rows 以及 foobar 值,其中包含连续 rows 之间的随机值。

开始时间应该是每个id的最早的timestamp,结束时间应该是每个id的最新timestamp

所以输出会是这样的。

timestamp            id  foo  bar
2019-04-14 00:00:10  1   0.10 0.05
2019-04-14 00:02:10  1   0.14 0.06
2019-04-14 00:04:10  1   0.11 0.06
2019-04-14 00:06:10  1   0.29 0.07
2019-04-14 00:08:10  1   0.22 0.09
2019-04-14 00:10:02  1   0.30 0.10
2019-04-14 00:00:00  2   0.80 0.50
2019-04-14 00:02:00  2   0.45 0.48
2019-04-14 00:04:00  2   0.52 0.42
2019-04-14 00:06:00  2   0.74 0.48
2019-04-14 00:08:00  2   0.41 0.45
2019-04-14 00:10:00  2   0.40 0.40

我可以重新索引 timestamp 列并创建其他 timestamp 行(例如 Pandas create new date rows and forward fill column values )。

但我似乎无法理解如何计算连续行之间的 foobar 的随机值。

如果有人能指出我正确的方向,我将不胜感激!

最佳答案

最后,你需要的是使用date_rangeDataFrame.reindexDatetimeIndex 的第一个和最后一个值:

df['timestamp'] = pd.to_datetime(df['timestamp'])

df = (df.set_index('timestamp')
        .groupby('id')['foo','bar']
        .apply(lambda x: x.reindex(pd.date_range(x.index[0], x.index[-1], periods=6))))

然后创建与原始大小相同的辅助 DataFrame 和 DataFrame.fillna缺失值:

df1 = pd.DataFrame(np.random.rand(*df.shape), index=df.index, columns=df.columns)
df = df.fillna(df1)
print (df)
                                 foo       bar
id                                            
1  2019-04-14 00:00:10.000  0.100000  0.050000
   2019-04-14 00:02:08.400  0.903435  0.755841
   2019-04-14 00:04:06.800  0.956002  0.253878
   2019-04-14 00:06:05.200  0.388454  0.257639
   2019-04-14 00:08:03.600  0.225535  0.195306
   2019-04-14 00:10:02.000  0.300000  0.100000
2  2019-04-14 00:00:00.000  0.100000  0.050000
   2019-04-14 00:02:00.000  0.180865  0.327581
   2019-04-14 00:04:00.000  0.417956  0.414400
   2019-04-14 00:06:00.000  0.012686  0.800948
   2019-04-14 00:08:00.000  0.716216  0.941396
   2019-04-14 00:10:00.000  0.300000  0.100000

关于python-3.x - 在 pandas 数据框中的行之间添加随机数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675347/

相关文章:

python - while 循环中 try/except 的较短版本?

python - 将 static() 添加到 urlpatterns 只能通过附加到列表来工作

Python ctype : char array to c function is not getting updated when the c function writes values to it

python - Pygame 暂停时显示文本

python - 在 CSV 文件 python 中添加新行和现有迭代行

python - Pandas groupby 和多列的加权和

python - 修改时间戳以按 ID 排序

python - Python中是否有相当于//运算符的上限?

python - Pandas - 为 Pandas 中的每个组插入空白行

python - 当没有这样的命名列时,SQLite 给出找不到列的错误