【问题标题】:Replicating rows in pandas dataframe by column value and add a new column with repetition index按列值复制熊猫数据框中的行并添加具有重复索引的新列
【发布时间】:2023-03-24 12:01:01
【问题描述】:

我的问题类似于here 提出的问题。我有一个数据框,我想重复数据框的每一行k 次数。除此之外,我还想创建一个值0k-1 的列。所以

import pandas as pd

df = pd.DataFrame(data={
  'id': ['A', 'B', 'C'],
  'n' : [  1,   2,   3],
  'v' : [ 10,  13,   8]
})

what_i_want = pd.DataFrame(data={
  'id': ['A', 'B', 'B', 'C', 'C', 'C'],
  'n' : [ 1, 2, 2, 3, 3, 3],
  'v' : [ 10,  13, 13, 8, 8, 8],
  'repeat_id': [0, 0, 1, 0, 1, 2]
})

下面的命令完成了一半的工作。我正在寻找添加repeat_id 列的熊猫方式。

df.loc[df.index.repeat(df.n)]

【问题讨论】:

  • 你的“一半工作”正是我想要的!

标签: python pandas dataframe


【解决方案1】:

使用GroupBy.cumcountcopy 避免SettingWithCopyWarning

如果您稍后修改 df1 中的值,您会发现修改不会传播回原始数据 (df),并且 Pandas 会发出警告。

df1 = df.loc[df.index.repeat(df.n)].copy()
df1['repeat_id'] = df1.groupby(level=0).cumcount()
df1 = df1.reset_index(drop=True)
print (df1)
  id  n   v  repeat_id
0  A  1  10          0
1  B  2  13          0
2  B  2  13          1
3  C  3   8          0
4  C  3   8          1
5  C  3   8          2

【讨论】:

  • 感谢您的快速回复!显然我只能在 10 分钟后接受答案:D
  • @kampta - 非常好的问题(inut,数据,输出数据,你尝试什么),不幸的是,这些天在 SO 中并不经常......
  • 如果你不copy()会怎样?我很难看出这样做有什么问题。
  • @FHTMitchell - 我得到SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  • @jezrael 是的,我也收到了警告。无论如何我继续,df 什么也没发生。奇数。
猜你喜欢
  • 1970-01-01
  • 2022-01-08
  • 2021-11-30
  • 1970-01-01
  • 2022-01-23
  • 2022-11-15
  • 2014-10-01
  • 2018-10-14
相关资源
最近更新 更多