【发布时间】:2022-01-02 05:02:53
【问题描述】:
这是Python pandas most common value over rolling date window 帖子的后续问题。我有一个类似的问题,给定的解决方案不起作用。任何人都可以评论!谢谢
我正在尝试为我的电源状态数据获取滚动窗口多数类,以便忽略一次性读数。在这篇文章Apply mode operation on categorical data in SQL 的帮助下,我在 SQL 中实现了类似的功能。可重现的数据和代码如下。
熊猫系列:
x = pd.Series(['EDC','EDC','EDC','DG','DWN','DWN','EDC','DWN','DWN','DWN','EDC','DWN'],name='Power_State')
x
0 EDC
1 EDC
2 EDC
3 DG
4 DWN
5 DWN
6 EDC
7 DWN
8 DWN
9 DWN
10 EDC
11 DWN
Name: Power_State, dtype: object
代码:
from scipy.stats import mode
x.rolling(window=7).apply(lambda x: mode(x)[0])
错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\window\rolling.py in _prep_values(self, values)
322 try:
--> 323 values = ensure_float64(values)
324 except (ValueError, TypeError) as err:
pandas\_libs\algos_common_helper.pxi in pandas._libs.algos.ensure_float64()
ValueError: could not convert string to float: 'EDC'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\window\rolling.py in _apply_series(self, homogeneous_func, name)
403 try:
--> 404 values = self._prep_values(obj._values)
405 except (TypeError, NotImplementedError) as err:
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\window\rolling.py in _prep_values(self, values)
324 except (ValueError, TypeError) as err:
--> 325 raise TypeError(f"cannot handle this type -> {values.dtype}") from err
326
TypeError: cannot handle this type -> object
The above exception was the direct cause of the following exception:
DataError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_6220/2483769170.py in <module>
1 from scipy.stats import mode
2
----> 3 x.rolling(window=7).apply(lambda x: mode(x)[0])
【问题讨论】: