首页 > 解决方案 > 将计数的行值扩展为单独的行,在 python 中添加不同的 ID

问题描述

我有一个包含多行和多列的数据集,但是在标记为“数字”的列中,我希望删除聚合并将其分成自己的唯一计数。我还希望添加一列,为该计数提供唯一 ID。

数据

location    name    type    number  year
ny          hello   he      1       2021
ny          bye     by      0       2021
ny          ok      o       2       2021
ca          hi      h       1       2021

期望的

location    name    type    number  year    count
ny          hello   he      1       2021    he1
ny          bye     by      0       2021    by1
ny          ok      o       1       2021    o1
ny          ok      o       1       2021    o2
ca          hi      h       1       2021    h1

字符串 'ok' 现在被分成不同的行,而不是被聚合为 2。'number ' 列中的值现在被分成 2 个不同的行,以及不同的计数 ID(基于 'name'列)而不是聚合。

正在做

df = df1.reindex(df1.index.repeat(df1['number'])).assign(number=1)
df['count'] = df['type'] + '0' + (df.groupby(['location', 'name', 'type', 'number', 'year']).cumcount() + 1).astype(str)
df

我得到了 SO 成员的帮助,但是,在此示例中,如果数字列中的值为 0,我将如何解释?我还在研究这个。

任何建议或意见表示赞赏

标签: pythonpandasnumpy

解决方案


想法是仅重复的拆分值number更大1,然后添加行number=0,1并排序以进行原始排序:

m = df1['number'].gt(1)
df2 = df1[m]
df = (pd.concat([df2.reindex(df2.index.repeat(df2['number'])).assign(number=1),
                 df1[~m]]).sort_index())

df['count'] = df['type'] + '0' + (df.groupby(['location', 'name', 'type', 'number', 'year']).cumcount() + 1).astype(str)

print (df)
  location   name type  number  year count
0       ny  hello   he       1  2021  he01
1       ny    bye   by       0  2021  by01
2       ny     ok    o       1  2021   o01
2       ny     ok    o       1  2021   o02
3       ca     hi    h       1  2021   h01

推荐阅读