根据 pandas 中连续行的值替换列值

Replace column values according to values of consecutive rows in pandas

我有一个数据框 df_in 定义如下:

import pandas as pd
dic_in = {'A':['aa','bb','cc','dd','ee','ff','gg','uu','xx','yy','zz'],
       'B':['200','200','200','400','400','500','700','700','900','900','200'],
       'C':['da','cs','fr','fs','se','at','yu','j5','31','ds','sz']}
df_in = pd.DataFrame(dic_in) 

我想调查列 B,以便为所有具有相同连续值的行分配一个新值(根据我将要描述的特定规则)。我举个例子更清楚:前三个rows['B']等于200。因此,他们都将分配编号 1;第四个和第五个 row['B'] 等于 400 因此它们将被分配编号 2。该过程重复直到结束。 最终结果 (df_out) 应如下所示:

# BEFORE #                # AFTER #
In[121]:df_in             In[125]df_out
Out[121]:                 Out[125]: 
     A    B   C                A  B   C
0   aa  200  da           0   aa  1  da
1   bb  200  cs           1   bb  1  cs
2   cc  200  fr           2   cc  1  fr
3   dd  400  fs           3   dd  2  fs
4   ee  400  se           4   ee  2  se
5   ff  500  at           5   ff  3  at
6   gg  700  yu           6   gg  4  yu
7   uu  700  j5           7   uu  4  j5
8   xx  900  31           8   xx  5  31
9   yy  900  ds           9   yy  5  ds
10  zz  200  sz           10  zz  6  sz

通知

你能建议我使用 pandas 实现这样的结果的聪明方法吗?

PS:手动映射值没有帮助,因为这是一个测试用例,最终我将有数千行要映射。它应该是自动的。

可以通过ne shifted column and then use cumsum比较:

print (df_in.B.ne(df_in.B.shift()))
0      True
1     False
2     False
3      True
4     False
5      True
6      True
7     False
8      True
9     False
10     True
Name: B, dtype: bool

df_in.B = df_in.B.ne(df_in.B.shift()).cumsum()
#same as !=, but 'ne' is faster
#df_in.B = (df_in.B != df_in.B.shift()).cumsum()
print (df_in)
     A  B   C
0   aa  1  da
1   bb  1  cs
2   cc  1  fr
3   dd  2  fs
4   ee  2  se
5   ff  3  at
6   gg  4  yu
7   uu  4  j5
8   xx  5  31
9   yy  5  ds
10  zz  6  sz