Pandas - iloc - 将值与下面的单元格进行比较

Pandas - iloc - comparing value to the cell below

以下table:

使用 Pandas - 我想实现 desired_output 列,当当前单元格下方的值不同时为 TRUE - 否则为 FALSE。

我尝试了以下代码 - 但出现错误。

df['desired_output']=df.two.apply(lambda x: True if df.iloc[int(x),1]==df.iloc[int(x+1),1] else False)

Series.ne with Series.shifted 值比较,第一个缺失值被原始值替换:

df = pd.DataFrame({'city':list('mmmssb')})

df['out'] = df['city'].ne(df['city'].shift(fill_value=df['city'].iat[0]))
print (df)
  city    out
0    m  False
1    m  False
2    m  False
3    s   True
4    s  False
5    b   True

对于较旧的 pandas 版本,如果使用 city 列中没有缺失值,则将第一个缺失值替换为 Series.fillna:

df['out'] = df['city'].ne(df['city'].shift().fillna(df['city']))
df['desired_output'] = df['city'].shift().bfill() != df['city']