首页 > 解决方案 > 使用字符串变量滚动

问题描述

考虑这个例子

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

不幸的是,下面的两种尝试都失败了

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能做的极限了吗?:) 谢谢!

标签: pythonpandas

解决方案


它看起来df.Rolling不会支持这一点。相反,您可以重新采样到 1 秒的间隔,然后将每个值与其后的行连接起来吗?

然后,您可以使用以下方法合并结果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

推荐阅读