python - 枚举 DataFrame 中的分类数据簇

标签 python pandas group-by categories enumeration

我有一个如下所示的 DataFrame:

    col1        col2    col3
0      0   string(0)  type B
1      1   string(1)  type B
2      2   string(2)  type B
3      3   string(3)  type B
4      4   string(4)  type A
5      5   string(5)  type A
6      6   string(6)  type A
7      7   string(7)  type A
8      8   string(8)  type A
9      9   string(9)  type A
10    10  string(10)  type A
11    11  string(11)  type A
12    12  string(12)  type B
13    13  string(13)  type B
14    14  string(14)  type A
15    15  string(15)  type A
16    16  string(16)  type A
17    17  string(17)  type A
18    18  string(18)  type A
19    19  string(19)  type A
20    20  string(20)  type A
21    21  string(21)  type B
22    22  string(22)  type B
23    23  string(23)  type B
24    24  string(24)  type A
25    25  string(25)  type A
26    26  string(26)  type A
27    27  string(27)  type A
28    28  string(28)  type A
29    29  string(29)  type A

我正在寻找最有效的方法来提取 col3 中的一种特定类型,并以这种方式枚举它们:

    col1        col2    col3  col4
0      0   string(0)  type B     0
1      1   string(1)  type B     0
2      2   string(2)  type B     0
3      3   string(3)  type B     0
12    12  string(12)  type B     1
13    13  string(13)  type B     1
21    21  string(21)  type B     2
22    22  string(22)  type B     2
23    23  string(23)  type B     2

枚举基于类型的集群。例如,col4中的0表示B类型的第0个簇。提前谢谢你们的帮助

编辑:生成上述 DataFrame 的代码如下:

import pandas as pd
n = 30
df = pd.DataFrame({'col1': [i for i in range(n)],
                   'col2': [f'string({i})' for i in range(n)]}
                    )

df['col3'] = 'type A'
df['col3'].iloc[[0,1,2,3,12,13,21,22,23]] = 'type B'#create col3 

最佳答案

首先与不等于Series.ne进行比较与 Series.shift ed值,然后过滤并添加Series.cumsum对于团体:

df['col4'] = df['col3'].ne(df['col3'].shift())
df = df[df['col3'] == 'type B']
df['col4'] = df['col4'].cumsum() - 1
print (df)
    col1        col2    col3  col4
0      0   string(0)  type B     0
1      1   string(1)  type B     0
2      2   string(2)  type B     0
3      3   string(3)  type B     0
12    12  string(12)  type B     1
13    13  string(13)  type B     1
21    21  string(21)  type B     2
22    22  string(22)  type B     2
23    23  string(23)  type B     2

关于python - 枚举 DataFrame 中的分类数据簇,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878231/

相关文章:

python - 根据索引将大型数据框中的数据除以较小数据框中的数据

python - 有没有办法为python中的每个实例创建唯一的字典属性

python - 获取按值分组的每行的百分比

python - 仅使用python置换最后一列

ruby-on-rails - Rails 4 where,order,group,count include zero's - postgresql

python - 将新列添加到 python pandas 中的分组对象

python - Python 3 OpenCV无法录制和保存视频

python - 似乎无法在 Python 3 中获取 POST 请求

python - 如何在 python 中获取小数点后超过 2 位的价格的 ItemException ex) $4.456

python - Pandas `DataFrameGroupBy` 和 `SeriesGroupBy`