简体   繁体   English

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

[英]How to match previous row value in a same column using df.iterrows()?

I am trying to match previous row value with a particular value using index number.我正在尝试使用索引号将前一行值与特定值匹配。 But i don't know how to implement this.但我不知道如何实现这一点。 Could you please help me how to do this?你能帮我怎么做吗?

Example:例子:

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

code i am trying:我正在尝试的代码:

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

Error:错误:

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

You should try "shift()"你应该试试“shift()”

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

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

output:输出:

0 alka
4 alka
5 alka

you can try a vectorized solution:您可以尝试矢量化解决方案:

np.where((df['operator'].isna()) & (df['operator'].shift() != 'AND') & (df['operator_type'] == '='))[0]

The result:结果:

pd.DataFrame({'type':'alka'}, 
             index=np.where((df['operator'].isna()) & (df['operator'].shift() != 'AND') & (df['operator_type'] == '='))[0])

OUT:
  type
0 alka
4 alka
5 alka

As the error says , it is just syntax errors.正如错误所说,这只是语法错误。 there are better ways to do what you are trying to do but for now just make the following change有更好的方法来做你想做的事,但现在只做以下改变

   if row['Operator'] == None and row['operator_type'] == '=' and row['Operator'].(index-1).values != 'AND':

to

   if row['Operator'] == None and row['operator_type'] == '=' and row['Operator'][index-1]  != 'AND':

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM