2024-10-05 14:28:58 发布
网友
我在python中有一个dataframe,它的列如下:
Type A A B B B
我想根据类型的顺序将另一列添加到数据框中:
我用下面的命令在R中执行:
setDT(df)[ , Seq := seq_len(.N), by = rleid(Type) ]
我不知道怎么做,python。在
编辑更新的问题
df['seq'] = df.groupby('Type').cumcount() + 1 df
输出:
使用pd.factorize:
pd.factorize
import pandas as pd df['seq'] = pd.factorize(df['Type'])[0] + 1 df
Type seq 0 A 1 1 A 1 2 B 2 3 B 2 4 B 2
在pandas
pandas
(df.Type!=df.Type.shift()).ne(0).cumsum() Out[58]: 0 1 1 1 2 2 3 2 4 2 Name: Type, dtype: int32
更多信息
使用Series.rank
df['seq'] = df['Type'].rank(method = 'dense').astype(int) Type seq 0 A 1 1 A 1 2 B 2 3 B 2 4 B 2
编辑更新的问题
输出:
^{pr2}$使用
pd.factorize
:输出:
在
pandas
更多信息
^{pr2}$使用Series.rank
相关问题 更多 >
编程相关推荐