python - 如何创建一个数据框列,其中包含一个已存在列中最近 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 的每一行的索引列表,感谢您的帮助,谢谢
解决方案
让我们从加载数据开始:
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]
推荐阅读
- java - peek() 和 allMatch() 如何在 Java 8 Stream API 中协同工作
- ruby-on-rails - 为什么时间戳保存在 psql 中但无法访问?如何访问?
- google-analytics - 跟踪具有相同域但不同 URL 的流量
- swift - 更改我的 ObservableObject 实例的属性不会更新 View。代码:
- c# - C# textfile 创建/删除同一行中的文本间距
- bash - curl post命令的shell脚本有什么问题
- c# - 在 Microsoft.Azure.Cosmos.Table 中使用 TableEntity.Flatten 的正确方法是什么?
- rest - 需要反馈 REST URL 的质量
- php - 一个很奇怪的问题,windows10自动升级后无法用WAMP访问Localhost
- sql - 使用 NEAR 选择查询?