我有一组数据,如何将其时间戳重新采样为1秒间隔,并用0填充数据列(“UUT”除外)。
UUT Sent Received Latency(ms) Sum
DateTime
2018-01-25 15:03:05 uut-1 1 1 427 2
2018-01-25 15:03:05 uut-2 1 1 664 2
2018-01-25 15:03:17 uut-1 1 1 637 2
2018-01-25 15:03:17 uut-2 1 1 1229 2
2018-01-25 15:03:29 uut-1 1 1 1154 2
2018-01-25 15:03:29 uut-2 1 1 1148 2
2018-01-25 15:04:00 uut-1 1 1 279 2
输出如下内容:
UUT Sent Received Latency(ms) Sum
DateTime
2018-01-25 15:03:05 uut-1 1 1 427 2
2018-01-25 15:03:05 uut-2 1 1 664 2
2018-01-25 15:03:06 uut-1 0 0 0 0
2018-01-25 15:03:06 uut-2 0 0 0 0
2018-01-25 15:03:07 uut-1 0 0 0 0
2018-01-25 15:03:07 uut-2 0 0 0 0
2018-01-25 15:03:08 uut-1 0 0 0 0
2018-01-25 15:03:08 uut-2 0 0 0 0
....
2018-01-25 15:03:17 uut-1 1 1 637 2
2018-01-25 15:03:17 uut-2 1 1 1229 2
2018-01-25 15:03:18 uut-1 0 0 0 0
2018-01-25 15:03:18 uut-2 0 0 0 0
.....
最终目标是使用groupby('UUT')绘制每个UUT的时间与任何其他剩余列的关系(例如'已发送',已接收','延迟(毫秒)')
答案 0 :(得分:2)
它不是很整洁,但你可以用下面的代码做你想做的事。
<强> 1。再现强>
val maxDate: Option[String] = DB readOnly { implicit session =>
sql"select max(MyColumn) as MyColumn_max from MyTable"
.map(rs => rs.string("MyColumn_max")).first.apply()
}
<强> 2。操作强>
idx = ['2018-01-25 15:03:05', '2018-01-25 15:03:05', '2018-01-25 15:03:17', '2018-01-25 15:03:17','2018-01-25 15:03:29', '2018-01-25 15:03:29']
dt = pd.DatetimeIndex(idx)
arrays = [
dt,
['uut1', 'uut2', 'uut1', 'uut2', 'uut1', 'uut2']
]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
data = pd.DataFrame({
'a' : range(1, 7),
'b' : range(1, 7)},
index=index)
data_manipulated = data.reset_index('second')
for second, df_gb in data_manipulated.groupby('second'):
vars()['df_{}'.format(second)] = df_gb.resample('1s').first().fillna(0)
df_uut1['second'] = 'uut1'
df_uut2['second'] = 'uut2'
df_uut1['first'] = df_uut1.index.values
df_uut1.index = range(len(df_uut1))
df_uut2['first'] = df_uut2.index.values
df_uut2.index = range(len(df_uut2), len(df_uut2)*2)
第3。结果强>
这是你想要做的吗?同样,代码本身也不可读。我想你可以自己做得更好。
答案 1 :(得分:0)
我最终使用重新采样
data2 = data.reset_index(level=[1])
second a b
first
2018-01-25 15:03:05 uut1 1 1
2018-01-25 15:03:05 uut2 2 2
2018-01-25 15:03:17 uut1 3 3
2018-01-25 15:03:17 uut2 4 4
2018-01-25 15:03:29 uut1 5 5
2018-01-25 15:03:29 uut2 6 6
然后分组
grouped = data2.groupby('second')
<pandas.core.groupby.DataFrameGroupBy object at 0x0000000005AB6E48>
# the groupby dataframe looks something like this:
grouped.get_group('uut1')
second a b
first
2018-01-25 15:03:05 uut1 1 1
2018-01-25 15:03:17 uut1 3 3
2018-01-25 15:03:29 uut1 5 5
现在重新采样每个组并用0:
填充上采样数据grouped_df = grouped.get_group(key).resample('1S').asfreq(0)
最后,替换所有&#39; 0&#39;第二个条目是&uut1&#39; grouped_df [&#39; second&#39;] =&#39; uut1&#39;
最终的数据框如下所示:
grouped.get_group('uut1')
second a b
first
2018-01-25 15:03:05 uut1 1 1
2018-01-25 15:03:06 uut1 0 0
2018-01-25 15:03:07 uut1 0 0
2018-01-25 15:03:08 uut1 0 0
...
2018-01-25 15:03:27 uut1 0 0
2018-01-25 15:03:28 uut1 0 0
2018-01-25 15:03:29 uut1 5 5