Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用df.iterrows()匹配同一列中的上一行值?_Python_Python 3.x_Dataframe - Fatal编程技术网

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

Python 如何使用df.iterrows()匹配同一列中的上一行值?,python,python-3.x,dataframe,Python,Python 3.x,Dataframe,我正在尝试使用索引编号将前一行值与特定值匹配。 但我不知道如何实现这一点。 你能帮我怎么做吗 例如: operator_type Operator = None = AND = None = OR = None = None 我正在尝试的代码: for index, row in df.iterrows():

我正在尝试使用索引编号将前一行值与特定值匹配。 但我不知道如何实现这一点。 你能帮我怎么做吗

例如:

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
你应该试试“shift()”

输出:

0 alka
4 alka
5 alka

您可以尝试矢量化解决方案:

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

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

正如错误所说,这只是语法错误。有更好的方法来做你想做的事情,但现在只需做以下改变

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

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