python - 将计数的行值扩展为单独的行,在 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,我将如何解释?我还在研究这个。
任何建议或意见表示赞赏
解决方案
想法是仅重复的拆分值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
推荐阅读
- c - Printing multiple variables in single printf() statement
- symfony - Expected value of type for association field , got "double" instead
- oauth-2.0 - Cortana 技能 Oauth2 错误 AADSTS90014:请求正文必须包含以下参数:“范围”
- node.js - npm 运行生产错误我无法破译
- matlab - 如何在 Matlab 中创建动态约束
- java - 生成连通图 java
- python - 如何在 python 中加载 R 的 .rda 神经网络模型
- python - 直接通过 Python Shell 从文件中读取
- audio - WAV“数据”子块是如何构成的?
- laravel - Laravel 中的 Ajax 发布请求,返回 html