python - 熊猫数据框中出现重复低的行
问题描述
在以下数据集中,使用 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)
先感谢您。
解决方案
value_counts
与map
和一起使用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)
推荐阅读
- node.js - 在 Node.js 中验证 Azure idToken
- c++ - 编译时检查 trait 特化是否有唯一的 id
- angular - 无法从获取请求中获取数据
- javascript - 我在哪里放置标题(chart.js)?
- google-analytics - 如何将事件链接并提取到谷歌分析中的会话 ID?
- laravel - 如何排队 Laravel 5.7“电子邮件验证”电子邮件发送
- javascript - 单击窗口以在跨度上添加类
- wordpress - WordPress woo commerce 按品牌获取产品
- jenkins - 在 Jenkins 中获取变量的结构
- java - ubuntu更新后tomcat 8停止工作