【问题标题】:Creating a column with series of numbers in a dataframe (python)在数据框中创建包含一系列数字的列(python)
【发布时间】:2021-03-23 15:22:20
【问题描述】:

我有下表(df):

ColumnA ColumnB Blocks Groups
B 32 1 A1
E 99 2 A1
I 76 3 A1
l 55 4 A1
m 27 5 A1
A 12 1 A2
F 123 2 A2
k 80 3 A2
m 27 4 A2
n 67 5 A2
C 44 1 A3
H 87 2 A3
J 231 3 A3
n 67 4 A3
o 34 5 A4
D 76 1 A4
G 65 2 A4

我想添加另一个附加列,其中包含基于“组”列的 ID 列表。对于 A1 组,它应该是 101,102,103,... A2 它应该是 201, 202, 203,... 输出表应该如下所示:

ColumnA ColumnB Blocks Groups IDs
B 32 1 A1 101
E 99 2 A1 102
I 76 3 A1 103
l 55 4 A1 104
m 27 5 A1 105
A 12 1 A2 201
F 123 2 A2 202
k 80 3 A2 203
m 27 4 A2 204
n 67 5 A2 205
C 44 1 A3 301
H 87 2 A3 302
J 231 3 A3 303
n 67 4 A3 304
o 34 5 A4 401
D 76 1 A4 402
G 65 2 A4 403

到目前为止我尝试了什么?

n = 4
TGn = round(len(df)/n)
idx = set(df.index // TGn)
df['IDs'] = (((df.index // TGn) + 1) * 100) + df.groupby('Groups').cumcount() + 1

这与组名(A1、A2、A3、A4)不一致。我该怎么做?

【问题讨论】:

    标签: python dataframe numbers pandas-groupby series


    【解决方案1】:

    您可以使用str.slice(1) 提取组号,并将其转换为整数类型:

    df['IDs'] = df.groupby('Groups').cumcount() + df['Groups'].str.slice(1).astype('int64') * 100 + 1
    

    如果组名的数字部分前可能有多个字符,您可以使用str.replace:

    df['IDs'] = df.groupby('Groups').cumcount() + df.Groups.str.replace(
        r'.*?(\d+)', r'\1', regex=True).astype('int64') * 100 + 1
    

    【讨论】:

    • 非常感谢!但问题是原始数据有A11、A12、AB11、AB12。因此,如果我使用 str.slice(1) 会出现错误
    • @MuSu18 我的编辑应该足以处理 AB11 或 AB12,但在 A11 和 A12 之间没有区别。你应该给出一些关于你想如何处理它的精确度。
    【解决方案2】:

    尝试使用ngroup 为每个组分配相同的 ID。我将它们设为 100,200,... 等等,然后我将 cumcount() 结果添加到它们。

    x = df.groupby('Groups')
    y = x.ngroup().add(1).mul(100)
    z = x.cumcount()+1
    df['IDs'] = y+z
    

    df:

    ColumnA ColumnB Blocks Groups IDs
    0 B 32 1 A1 101
    1 E 99 2 A1 102
    2 I 76 3 A1 103
    3 l 55 4 A1 104
    4 m 27 5 A1 105
    5 A 12 1 A2 201
    6 F 123 2 A2 202
    7 k 80 3 A2 203
    8 m 27 4 A2 204
    9 n 67 5 A2 205
    10 C 44 1 A3 301
    11 H 87 2 A3 302
    12 J 231 3 A3 303
    13 n 67 4 A3 304
    14 o 34 5 A4 401
    15 D 76 1 A4 402
    16 G 65 2 A4 403

    编辑: 您也可以从 Groups (A1, A2....) 中获取组号。我在写答案时没有检查。

    df['IDs'] = (df.Groups.str.extract('(\d$)').astype(int).mul(100))[0] + df.groupby('Groups').cumcount()+1
    

    【讨论】:

    • 非常感谢!如何为 n 组更改此设置? n 是用户输入。
    猜你喜欢
    • 1970-01-01
    • 2015-05-18
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多