滚动字符串变量 [英] rolling with string variables
本文介绍了滚动字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑此示例
import pandas as pd
import numpy as np
df = pd.DataFrame({'mytime' : [pd.to_datetime('2018-01-01 14:34:12.340'),
pd.to_datetime('2018-01-01 14:34:13.0'),
pd.to_datetime('2018-01-01 14:34:15.342'),
pd.to_datetime('2018-01-01 14:34:16.42'),
pd.to_datetime('2018-01-01 14:34:28.742')],
'myvalue' : [1,2,np.NaN,3,1],
'mychart' : ['a','b','c','d','e']})
df.set_index('mytime', inplace = True)
df
Out[15]:
mychart myvalue
mytime
2018-01-01 14:34:12.340 a 1.0
2018-01-01 14:34:13.000 b 2.0
2018-01-01 14:34:15.342 c NaN
2018-01-01 14:34:16.420 d 3.0
2018-01-01 14:34:28.742 e 1.0
在这里,我想使用最近 2秒(而不是最后两个观察值)中的值concatenate
mychart
中的字符串.
Here I want to concatenate
the strings in mychart
using the values in the last 2 seconds (not the last two observations).
不幸的是,下面的两次尝试都失败了
Unfortunately, both attempts below fail miserably
df.mychart.rolling(window = '2s', closed = 'right').apply(lambda x: ' '.join(x), raw = False)
df.mychart.rolling(window = '2s', closed = 'right').apply(lambda x: (x + ' ').cumsum(), raw = False)
TypeError: cannot handle this type -> object
我们终于达到了Pandas 23.4
可以做什么的极限吗? :)
谢谢!
Are we finally hitting the limits of what Pandas 23.4
can do? :)
Thanks!
推荐答案
df.Rolling
似乎不支持此功能.相反,您是否可以每隔1秒重新采样一次,然后将每个值与其后的行连接起来?
It doesn't look like df.Rolling
will support this. Instead, can you resample to 1 sec intervals and then just concat every value with the row after it?
然后您可以使用merge_asof
将结果合并回去:
You can then merge the result back using merge_asof
:
v = df.resample('1s').agg(''.join)
pd.merge_asof(df,
v.add(v.shift(-1)).rename({'mychart': 'res'}, axis=1),
left_index=True,
right_index=True)
myvalue mychart res
mytime
2018-01-01 14:34:12.340 1.0 a ab
2018-01-01 14:34:13.000 2.0 b b
2018-01-01 14:34:15.342 NaN c cd
2018-01-01 14:34:16.420 3.0 d d
2018-01-01 14:34:28.742 1.0 e NaN
这篇关于滚动字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文