python - 使用字符串变量滚动
问题描述
考虑这个例子
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
能做的极限了吗?:) 谢谢!
解决方案
它看起来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
推荐阅读
- html - 如何使用类获取 div 内未命名嵌套 div 的内容?(使用 Scrapy 或 BeautifulSoup)
- spring-boot - 在不暴露端点的情况下访问 Spring Boot Actuator 内部 bean
- class - 在公共静态类中获取控件数据
- javascript - 如何将这行 JavaScript 转换为 TypeScript?
- javascript - RangeError:Angular 中超出了最大调用堆栈大小
- python - 使用python在没有csv模块的csv文件中添加数字
- django - 尝试将 django 表单字段呈现为 html 模板中脚本标记中的变量,但 javascript 不起作用
- docker - redis容器的自定义配置
- android - 未为 MediaProvider 调用 SyncAdapter onPerformSync
- python - 如何排序和导出python字典上所有重叠键值?