首页 > 解决方案 > 熊猫数据框中出现重复低的行

问题描述

在以下数据集中,使用 groupby(['Type']) count < 3 to 3 复制行的最佳方法是什么。df 是输入,df1 是我想要的结果。您会看到 df 中的第 3 行最后被复制了 2 次。这只是一个示例牌组。真实数据大约有 2000 万行和 400K 唯一类型,因此需要一种有效执行此操作的方法。

>>> df
  Type  Val
0    a    1
1    a    2
2    a    3
3    b    1
4    c    3
5    c    2
6    c    1
>>> df1
  Type  Val
0    a    1
1    a    2
2    a    3
3    b    1
4    c    3
5    c    2
6    c    1
7    b    1
8    b    1

想过使用类似下面的东西,但不知道编写函数的最佳方法。

df.groupby('Type').apply(func)

先感谢您。

标签: pythonpandas

解决方案


value_countsmap和一起使用repeat

counts = df.Type.value_counts()
repeat_map = 3 - counts[counts < 3]
df['repeat_num'] = df.Type.map(repeat_map).fillna(0,downcast='infer')
df = df.append(df.set_index('Type')['Val'].repeat(df['repeat_num']).reset_index(), 
               sort=False, ignore_index=True)[['Type','Val']]

print(df)

  Type  Val
0    a    1
1    a    2
2    a    3
3    b    1
4    c    3
5    c    2
6    c    1
7    b    1
8    b    1

注意: sort=False forappend存在于 中pandas>=0.23.0,如果使用较低版本,请删除。

编辑:如果数据包含多个 val 列,则将所有列列作为索引,除了一列并重复,然后将 reset_index 设置为:

df = df.append(df.set_index(['Type','Val_1','Val_2'])['Val'].repeat(df['repeat_num']).reset_index(), 
               sort=False, ignore_index=True)

推荐阅读