[英]Expand counted row value into separate rows, adding distinct ID in python
I have a dataset that has several rows and columns, however within the column labeled, 'number', I wish to remove the aggregation and separate this into its own unique count.我有一个包含多行和多列的数据集,但是在标记为“数字”的列中,我希望删除聚合并将其分成自己的唯一计数。 I also wish to add a column that gives this count a unique id.我还希望添加一列,为该计数提供唯一 ID。
Data数据
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
Desired期望的
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
The string 'ok' is now separated into distinct rows, versus being aggregated with a value of 2. The values in the 'number' column are now separated into 2 distinct rows, along with a distinct count ID (based on the 'name' column) instead of an aggregation.字符串 'ok' 现在被分成不同的行,而不是被聚合为 2。'number ' 列中的值现在被分成 2 个不同的行,以及不同的计数 ID(基于 'name'列)而不是聚合。
Doing正在做
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
I was helped by a SO member, however, in this example, how would I account for if values in the number column is 0?我得到了 SO 成员的帮助,但是,在此示例中,如果数字列中的值为 0,我将如何解释? I am still researching this.我还在研究这个。
Any suggestion or advice is appreciated任何建议或意见表示赞赏
Idea is split values for repeat only of number
is greater like 1
, then add rows with number=0,1
and sorting for original ordering:想法是仅重复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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.