Skip to main content
 首页 » 编程设计

python之Pandas :将单元格值与同一列下方的单元格值进行比较

2025年05月04日13xiaohuochai

我有一个包含以下列的数据框

import pandas as pd 
 
df = pd.DataFrame({'num': [1, 2, 2, 3, 4, 5, 6]}) 

我想创建一个列,使用 df['num'].shift() 将当前单元格值与其下方的单元格值进行比较,如果匹配,则该值应为 True 或 False。

预期输出:

   num  matches? 
0    1     False 
1    2      True 
2    2     False 
3    3     False 
4    4     False 
5    5     False 
6    6     False 

我无法找到遍历每个单元格并比较条件以及何时使用以下内容的最佳方法:

 
df['matches?'] = '' 
 
for i in range(len(df)): 
    if df['num'] == df['num'].shift(1): 
        df['matches?'] = True 
    else: 
        df['matches?'] = False 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

如何以最简单的方式实现这一点?

请您参考如下方法:

当您使用 shift 时,您不需要循环,该操作被矢量化并为您完成:

df['matches?'] = df['num'].shift(-1)==df['num'] 

输出:

    num    matches? 
0   1      False 
1   2      True 
2   2      False 
3   3      False 
4   4      False 
5   5      False 
6   6      False 

编辑

如果要保持循环逻辑:

for ix, row in df.iterrows(): 
    if ix < len(df)-1: 
        if df.loc[ix, 'num'] == df.loc[ix+1, 'num']: 
            df.loc[ix, 'matches?'] = True 
        else: 
            df.loc[ix, 'matches?'] = False 
    else: #last observation 
        df.loc[ix, 'matches?'] = False 

输出:

    num    matches? 
0   1      False 
1   2      True 
2   2      False 
3   3      False 
4   4      False 
5   5      False 
6   6      False