Pandas DataFrame:如何在滚动窗口上设置联合聚合 [英] Pandas DataFrame: How to do Set Union Aggregation over a rolling window

查看:248
本文介绍了Pandas DataFrame:如何在滚动窗口上设置联合聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其中一列包含一组ID,另一列包含日期:

I have a Dataframe that contains sets of ids in one column and dates in another:

import pandas as pd

df = pd.DataFrame([['2018-01-01', {1, 2, 3}],
                   ['2018-01-02', {3}],
                   ['2018-01-03', {3, 4, 5}],
                   ['2018-01-04', {5, 6}]],
                  columns=['timestamp', 'ids'])

df['timestamp'] = pd.to_datetime(df['timestamp'])
df.set_index('timestamp', inplace=True)

                     ids
timestamp               
2018-01-01     {1, 2, 3}
2018-01-02     {3}
2018-01-03     {3, 4, 5}
2018-01-04     {5, 6}

我正在寻找的功能是可以为我提供每天最近x天的ID.因此,假设x = 3,我希望结果为:

What I am looking for is a function that can give me the ids for the last x days per day. So, assuming x=3, I'd want the result to be:

                     ids
timestamp               
2018-01-01     {1, 2, 3}
2018-01-02     {1, 2, 3}
2018-01-03     {1, 2, 3, 4, 5}
2018-01-04     {3, 4, 5, 6}

我尝试过

df.rolling(3).agg(set.union)

但这会导致以下错误:

Traceback (most recent call last):
  File "C:\Users\m.manhertz\Envs\demo-8EG6nosu\lib\site-packages\pandas\core\window.py", line 222, in _prep_values
    values = _ensure_float64(values)
  File "pandas\_libs\algos_common_helper.pxi", line 3182, in pandas._libs.algos.ensure_float64
  File "pandas\_libs\algos_common_helper.pxi", line 3187, in pandas._libs.algos.ensure_float64
TypeError: float() argument must be a string or a number, not 'set'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\m.manhertz\Envs\demo-8EG6nosu\lib\site-packages\pandas\core\window.py", line 1561, in aggregate
    return super(Rolling, self).aggregate(arg, *args, **kwargs)
  File "C:\Users\m.manhertz\Envs\demo-8EG6nosu\lib\site-packages\pandas\core\window.py", line 321, in aggregate
    return self.apply(arg, raw=False, args=args, kwargs=kwargs)
  File "C:\Users\m.manhertz\Envs\demo-8EG6nosu\lib\site-packages\pandas\core\window.py", line 1580, in apply
    func, raw=raw, args=args, kwargs=kwargs)
  File "C:\Users\m.manhertz\Envs\demo-8EG6nosu\lib\site-packages\pandas\core\window.py", line 1003, in apply
    center=False, raw=raw)
  File "C:\Users\m.manhertz\Envs\demo-8EG6nosu\lib\site-packages\pandas\core\window.py", line 844, in _apply
    values = self._prep_values(b.values)
  File "C:\Users\m.manhertz\Envs\demo-8EG6nosu\lib\site-packages\pandas\core\window.py", line 225, in _prep_values
    "".format(values.dtype))
TypeError: cannot handle this type -> object

推荐答案

Pandas并非旨在将listsetdict之类的可迭代对象保存在pd.Series对象中.因此,您的逻辑不可矢量化.最好的选择可能是列表理解:

Pandas isn't designed to hold iterables such as list, set, dict within pd.Series objects. As such, your logic is not vectorisable. Your best option may be a list comprehension:

import pandas as pd

df = pd.DataFrame([['2018-01-01', {1, 2, 3}],
                   ['2018-01-02', {3}],
                   ['2018-01-03', {3, 4, 5}],
                   ['2018-01-04', {3, 6}]],
                  columns=['timestamp', 'ids'])

df['timestamp'] = pd.to_datetime(df['timestamp'])
df.set_index('timestamp', inplace=True)

df['ids'] = [set.union(*df.iloc[max(0, i-2): i+1, 0]) for i in range(len(df.index))]

print(df)

                        ids
timestamp                  
2018-01-01        {1, 2, 3}
2018-01-02        {1, 2, 3}
2018-01-03  {1, 2, 3, 4, 5}
2018-01-04     {3, 4, 5, 6}

这篇关于Pandas DataFrame:如何在滚动窗口上设置联合聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆