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':