首页 > 解决方案 > 如何创建一个数据框列,其中包含一个已存在列中最近 3 次 True 的索引列表?

问题描述

我不太确定我是否设法正确地表达了这个问题,但我想知道如何创建一个列来跟踪最近 3 次在另一列中有一个 True,我的数据框看起来有点像这样,日期为索引, 认为

2021-03-22            True       [None, None, None]  
2021-03-23            True       [None, None, None]   
2021-03-24            True       [2021-03-22, 2021-03-23, 2021-03-24]   
2021-03-25            False      [None, None, None]   
2021-03-26            True       [2021-03-23, 2021-03-24, 2021-03-26] 

上面的最后一列是我希望新列的格式。前两行是 NaN,因为我首先需要至少 3 行数据来计算模式,第 4 行是 NaN,因为我只需要第二列包含 True 时的模式。

我实际上需要这个来对其他列进行更大的计算,但首先我需要第二列值为 True 的每一行的索引列表,感谢您的帮助,谢谢

标签: pythonpandasdataframe

解决方案


让我们从加载数据开始:

import pandas as pd
from io import StringIO
data = StringIO(
'''
2021-03-22            True 
2021-03-23            True 
2021-03-24            True 
2021-03-25            False
2021-03-26            True
''')
df = pd.read_csv(data ,sep = '\s+', header=None)
df

所以它看起来像这样:


    0           1
0   2021-03-22  True
1   2021-03-23  True
2   2021-03-24  True
3   2021-03-25  False
4   2021-03-26  True

现在应用逻辑:

df.loc[df[1] == True, 2] = [w.to_list() for w in df.loc[df[1] == True, 0].rolling(3)]
df.loc[df[1] == False, 2] = ''

我们得到


    0           1       2
0   2021-03-22  True    [2021-03-22]
1   2021-03-23  True    [2021-03-22, 2021-03-23]
2   2021-03-24  True    [2021-03-22, 2021-03-23, 2021-03-24]
3   2021-03-25  False   
4   2021-03-26  True    [2021-03-23, 2021-03-24, 2021-03-26]

现在按照要求用无替换“短”列表

df[2]  = df.apply(lambda row: row[2] if len(row[2])==3 else [None, None, None], axis=1)
df

我们得到

    0           1       2
0   2021-03-22  True    [None, None, None]
1   2021-03-23  True    [None, None, None]
2   2021-03-24  True    [2021-03-22, 2021-03-23, 2021-03-24]
3   2021-03-25  False   [None, None, None]
4   2021-03-26  True    [2021-03-23, 2021-03-24, 2021-03-26]

推荐阅读