Skip to content Skip to sidebar Skip to footer

Rolling With String Variables

Consider this example 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(

Solution 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?

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

Solution 2:

A little bit over thinking , and only work for when rolling result have two concat together , you can work a little bit more and build up your own function and include all the possible rolling number and size

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

Post a Comment for "Rolling With String Variables"