以最有效的方式比较两个 pandas DataFrame

2024-01-09

让我们考虑两个 pandas 数据框:

import numpy as np
import pandas as pd

df = pd.DataFrame([1, 2, 3, 2, 5, 4, 3, 6, 7])

check_df = pd.DataFrame([3, 2, 5, 4, 3, 6, 4, 2, 1])

如果想做以下事情:

  1. If df[1] > check_df[1] or df[2] > check_df[1] or df[3] > check_df[1]然后我们分配给 df 1,否则分配给 0
  2. If df[2] > check_df[2] or df[3] > check_df[2] or df[4] > check_df[2]然后我们分配给 df 1,否则分配给 0
  3. 我们对 DataFrame 的末尾应用相同的算法

我的原始代码如下:

df_copy = df.copy()
for i in range(len(df) - 3):
    moving_df = df.iloc[i:i+3]
    if (moving_df >check_df.iloc[i]).any()[0]:
        df_copy.iloc[i] = 1
    else:
        df_copy.iloc[i] = -1
df_copy


    0
0   -1
1   1
2   -1
3   1
4   1
5   -1
6   3
7   6
8   7

如果有可能在没有循环的情况下做到这一点,您能给我一个建议吗?


IIUC,这很容易通过rolling.min:

df['out'] = np.where(df[0].rolling(N, min_periods=1).max().shift(1-N).gt(check_df[0]),
                     1, -1)

output:

   0  out
0  1   -1
1  2    1
2  3   -1
3  2    1
4  5    1
5  4   -1
6  3    1
7  6   -1
8  7   -1

保持最后的项目不变:

m = df[0].rolling(N).max().shift(1-N)
df['out'] = np.where(m.gt(check_df[0]),
                     1, -1)
df['out'] = df['out'].mask(m.isna(), df[0])

output:

   0  out
0  1   -1
1  2    1
2  3   -1
3  2    1
4  5    1
5  4   -1
6  3    1
7  6    6
8  7    7
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以最有效的方式比较两个 pandas DataFrame 的相关文章

随机推荐