首页 > 解决方案 > 使用 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'))

标签: pythonpandas

解决方案


bfill/ffill让我们尝试limit

(df.hits.bfill(limit=2).ffill(limit=2) & df['max']).sum()
# out 2

推荐阅读