如何使用df.iterrows()匹配同一列中的前一行值?

问题描述 投票:1回答:1

我正在尝试使用索引号将上一行值与特定值进行匹配。但我不知道如何实现这一目标。您能帮我怎么做吗?

示例:

operator_type   Operator
    =            None
    =            AND
    =            None
    =            OR
    =            None
    =            None

我正在尝试的代码:

for index, row in df.iterrows():
       if row['Operator'] == None and row['operator_type'] == '=' and row['Operator'].(index-1).values != 'AND':
             print('alka')

错误:

File "imed_cons_new.py", line 68
    if row['and_or_not_oprtor'] == None and row['operator_type'] == '=' and row['and_or_not_oprtor'].(index-1).values != 'AND':
                                                                                                     ^
SyntaxError: invalid syntax
python python-3.x dataframe
1个回答
0
投票

您应该尝试“ shift()”

df['preview'] = df['Operator'].shift()

for index, row in df.iterrows():
   if row['Operator'] == None and row['operator_type'] == '=' and row['preview'] != 'AND':
   print(index,'alka')

输出:

0 alka
4 alka
5 alka
© www.soinside.com 2019 - 2024. All rights reserved.