我有一个带有日期时间索引的数据帧、一个要按其分组的列和一个包含整数集的列:

import pandas as pd

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

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

            group        ids
timestamp
2018-01-01      1  {1, 2, 3}
2018-01-02      1        {3}
2018-01-03      1  {3, 4, 5}
2018-01-04      1     {5, 6}
2018-01-01      2        {7}
2018-01-02      2        {8}
2018-01-03      2        {9}
2018-01-04      2       {10}

在每一组中,我想在过去的x天内建立一个滚动集联盟。所以假设X=3,结果应该是:
            group              ids
timestamp
2018-01-01      1        {1, 2, 3}
2018-01-02      1        {1, 2, 3}
2018-01-03      1  {1, 2, 3, 4, 5}
2018-01-04      1     {3, 4, 5, 6}
2018-01-01      2              {7}
2018-01-02      2           {7, 8}
2018-01-03      2        {7, 8, 9}
2018-01-04      2       {8, 9, 10}

从对my previous question的回答中,我很清楚如何在不分组的情况下完成这项工作,因此我提出了目前的解决方案:
grouped = df.groupby('group')
new_df = pd.DataFrame()
for name, group in grouped:
    group['ids'] = [
        set.union(*group['ids'].to_frame().iloc(axis=1)[max(0, i-2): i+1,0])
        for i in range(len(group.index))
    ]
    new_df = new_df.append(group)

这给出了正确的结果,但看起来相当笨拙,并给出以下警告:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

不过,提供的链接中的文档似乎并不完全符合我的实际情况。(至少在这种情况下,我无法理解。)
我的问题是:如何改进此代码,使其干净、高效,并且不抛出警告消息?

最佳答案

作为mentioned in the docs,不要在循环中使用pd.DataFrame.append;这样做会很昂贵。
相反,使用list并馈送到pd.concat
您可以通过在列表中创建数据副本来避免SettingWithCopyWarning,即在列表理解中通过assign+iloc避免chained indexing

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

res = pd.concat(L)

print(res)

            group              ids
timestamp
2018-01-01      1        {1, 2, 3}
2018-01-02      1        {1, 2, 3}
2018-01-03      1  {1, 2, 3, 4, 5}
2018-01-04      1     {3, 4, 5, 6}
2018-01-01      2              {7}
2018-01-02      2           {8, 7}
2018-01-03      2        {8, 9, 7}
2018-01-04      2       {8, 9, 10}

09-12 10:51