滚动字符串变量

时间:2018-10-05 02:10:56

标签: python pandas

考虑此示例

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可以做什么的极限了吗? :) 谢谢!

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

稍加思考,仅在滚动结果同时包含两个concat时起作用,您可以进行更多工作并构建自己的功能,并包括所有可能的滚动数和大小

df['newmap']=np.arange(len(df)) # vassign new column
d=dict(zip(df['newmap'].astype(str),df.mychart))# create dict for replace
df['rollingstring']=df.newmap.rolling(window = '2s', closed = 'right').sum().astype(int)

df['newmap']=df['newmap'].astype(str)

df['rollingstring']=df['rollingstring'].astype(str)
# this part can be replace with a function⬇⬇⬇⬇⬇
df.loc[df.rollingstring!=df.newmap,'rollingstring']=(df.rollingstring.astype(int).sub(1)/2).astype(int).astype(str)+','+(df.rollingstring.astype(int).add(1)/2).astype(int).astype(str)


df.rollingstring.replace(d,regex=True)
Out[355]: 
mytime
2018-01-01 14:34:12.340      a
2018-01-01 14:34:13.000      b
2018-01-01 14:34:15.342      c
2018-01-01 14:34:16.420    c,d
2018-01-01 14:34:28.742      e
Name: rollingstring, dtype: object