我有一个像这样的 pandas 数据框。其中包含 timestamp
、id
、foo
和 bar
。
timestamp
数据大约每 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
以及 foo
和 bar
值,其中包含连续 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 )。
但我似乎无法理解如何计算连续行之间的 foo
和 bar
的随机值。
如果有人能指出我正确的方向,我将不胜感激!
最佳答案
最后,你需要的是使用date_range
与 DataFrame.reindex
按 DatetimeIndex
的第一个和最后一个值:
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/