python - 使用 pandas 确定两列中的值是否彼此接近
问题描述
这是我的数据框:
max hits
0 NaN NaN
1 NaN NaN
2 NaN True (bad)
3 NaN NaN
4 NaN NaN
5 NaN NaN
6 True NaN
7 NaN True (good)
8 NaN NaN
9 NaN NaN
10 NaN True (good)
11 True NaN
12 NaN NaN
13 NaN NaN
我想计算 'hits' 列中有多少 True 值与 'max' 列中的 True 值相近。接近标准是上两步和下两步。所以在我的例子中答案是 2。
现在我这样算:
# get indexes of True values in hits column
indexes = df.dropna(subset = ['hits']).index
count = 0
for index in indexes:
df_slice = df_work.iloc [index-2 : index+2+1].dropna(subset = ['max'])
if len(df_slice) > 0:
count += 1 # True in 'hits' is close to True value in 'max'
它按预期工作,但非常缓慢。我的 DataFrame 非常大,我松了很多次。有更快的方法吗?
更新:它开始使用这种方法飞行:
df.hits.fillna(method='bfill', inplace=True, limit=2)
df.hits.fillna(method='ffill', inplace=True, limit=2)
count = len (df.dropna(subset=['hits', 'max'], inplace=False, how = 'any'))
解决方案
bfill/ffill
让我们尝试limit
:
(df.hits.bfill(limit=2).ffill(limit=2) & df['max']).sum()
# out 2
推荐阅读
- flutter - Flutter 运行或更新应用后文件路径发生变化
- kdb - 如何在 KDB+ 中按时间排序结果
- php - 显示包含选项中数据的所有记录
- java - 从长期价值中获取时间
- angular - 使用 Observables 从 httpClient 返回一个字符串数组
- python - 使用 Python,我将如何返回行 # 以及我的 SQLite DB 中的描述?
- java - Hibernate QuerySyntaxException:未映射
- perl - 将 coderef 传递给 sort() 问题
- arrays - 如果数组有一些数据已经反应原生,如何将数据推送到数组数组中?
- discord - Discord.js - 检测消息是否包含图像或链接