用连续的相应数值替换 pandas 数据框中的多个重复字符串

Substituting multiple repetitive strings in pandas dataframe with consecutive respective numeric values

我问过 ,但现在想在 Python 中做同样的事情。

我有一个包含 10000 行的数据框。

Author  Value
aaa     111
aaa     112
bbb     156
bbb     165
ccc     543
ccc     256

每个作者有 4 行,所以我有 2500 个作者。

我想将所有字符串替换为数值。理想情况下 tidyverse.

预期产出

Author  Value
1       111
1       112
2       156
2       165
3       543
3       256
---------
2500    451
2500    234

谢谢!

使用pd.factorize():

df['Author'] = pd.factorize(df['Author'])[0] + 1

另一种方式,对连续列值的布尔值求和

df['Author'] = (df['Author']!=df['Author'].shift()).cumsum()