python - 在 python 中将聚合值拆分为不同的计数,返回新行

标签 python pandas numpy

我的 Excel 文件 df 中有数据,它保存每个 ID 的聚合值。我希望将其分解为不同的计数,并为每个计数创建一个新记录。

数据

    A    B    C

    2    3    1

所需

 count   ID

  1      A01

  1      A02
  
  1      B01

  1      B02

  1      B03

  1      C01

正在做:

import pandas as pd
from numpy.random import randint

df = pd.DataFrame(columns=['A', 'B', 'C'])
     for i in range(5):
     df.loc[i] = ['ID' + str(i)] + list(randint(10, size=2))

我想我可以这样做,但是,这并不是连续堆叠所有必要的 ID。

如有任何建议或建议,我们将不胜感激。

最佳答案

让我们尝试 melt 来 reshape 数据,reindex + repeat 来复制行,以及 groupby + cumcount + zfill 创建后缀:

import pandas as pd

df = pd.DataFrame({'A': {0: 2}, 'B': {0: 3}, 'C': {0: 1}})

# Melt Table Into New Form
df = df.melt(col_level=0, value_name='count', var_name='ID')
# Repeat Based on Count
df = df.reindex(df.index.repeat(df['count']))
# Set Count To 1
df['count'] = 1

# Add Suffix to Each ID
df['ID'] = df['ID'] + (
    (df.groupby('ID').cumcount() + 1)
        .astype(str)
        .str.zfill(2)
)

# Reorder Columns
df = df[['count', 'ID']]

print(df)

df:

   count   ID
0      1  A01
0      1  A02
1      1  B01
1      1  B02
1      1  B03
2      1  C01

关于python - 在 python 中将聚合值拆分为不同的计数,返回新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67509127/

相关文章:

python - 如何使用 excelwriter 将标题中的文本换行?

python - 缩短字典中键的长度

python - (numpy) __array_wrap__ 做什么?

python - 具有可变数量因子的 Numpy 向量化求和

python - 类型错误 : unsupported operand type(s) for -: 'numpy.ndarray' and 'numpy.ndarray'

python:为多个问题导入随机数

python - 在 Pandas 中设置最大字符串长度

python - 从头开始计算 3 个 numpy 数组之间的欧氏距离

python - 定义 Apache Beam 管道的正确方法

Python Selenium 找到输入元素但无法发送键