python中dataframe中的序列长度

2024-10-05 14:28:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个dataframe,它的列如下:

Type   
 A        
 A 
 B
 B
 B

我想根据类型的顺序将另一列添加到数据框中:

^{pr2}$

我用下面的命令在R中执行:

setDT(df)[ , Seq := seq_len(.N), by = rleid(Type) ] 

我不知道怎么做,python。在


Tags: 数据命令类型dataframedfbylen顺序
3条回答

编辑更新的问题

df['seq'] = df.groupby('Type').cumcount() + 1
df

输出:

^{pr2}$

使用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

(df.Type!=df.Type.shift()).ne(0).cumsum()
Out[58]: 
0    1
1    1
2    2
3    2
4    2
Name: Type, dtype: int32

更多信息

^{pr2}$

使用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

相关问题 更多 >