【问题标题】:Pandas GroupBy- Remove groups with less than 2 itemsPandas GroupBy- 删除少于 2 个项目的组
【发布时间】:2021-04-11 08:06:45
【问题描述】:

我有一个 ID 为 5 列的 Pandas DataFrame。

希望获得仅包含 2 个或更多 ID 的组的输出。或者至少,按 ID 的数量(降序)排序。

for key, item in grouped:

    print(key)
    print(item['ID'])
    print()

通过上述方法来实现一长串键及其 ID,想知道我是否需要在其中合并某种 size() 命令来实现所需的输出?

寻找这样的输出:

('Met', 59.0, 0.0, 0.0, 196.0, 66.0)
702     510000261554
1184    510000247456
Name: ID, dtype: int64

对编码非常陌生,因此非常感谢任何帮助!

【问题讨论】:

  • 嘿,你能提供一个你的起始和分组数据帧的例子吗?
  • @Fred 很烦人,这是敏感数据,所以我不能再详细说明了。我的起始 DataFrame 是一个非常简单的组件 ID、它们的尺寸和材料的表格。然后我根据尺寸和材料对这些组件 ID 进行分组,其想法是获得本质上相同组件的 ID。我实际上无法打印分组的 DataFrame,我不得不使用上面的“For key,item in grouped”循环来获得任何输出。在此之前,我得到了这个:

标签: pandas dataframe group-by pandas-groupby


【解决方案1】:

根据我的理解,您的数据集如下所示:

print(df)

| id | length | width | material | ... |
+----+--------+-------+----------+-----+
| 1  | 100    | 50    | plastic  | ... |
| 1  | 100    | 50    | plastic  | ... |
| 2  | 100    | 50    | wood     | ... |
| 2  | 100    | 100   | wood     | ... |

然后你按id, length, width, material分组?

如果您随后应用.size(),这将返回一个带有多索引的系列。然后,您可以将此系列过滤到大小大于 1 的行。

# Group the data

s = df.groupby(["id", "length", "width", "material"]).size()

print(s)

| (id, length, width, material) |   |
+-------------------------------+---+
| (1, 100, 50, plastic)         | 2 |
| (2, 100, 50, wood)            | 1 |
| (2, 100, 100, wood)           | 1 |



# Get all groups with more than 1 row

more_than_1_row = s[s>1]

print(more_than_1_row)

| (id, length, width, material) |   |
+-------------------------------+---+
| (1, 100, 50, plastic)         | 2 |


# Convert the Series to a DataFrame

df_more_than_1_row = more_than_1_row.reset_index()

print(df_more_than_1_row)

| id | length | width | material |   |
+----+--------+-------+----------+---+
| 1  | 100    | 50    | plastic  | 2 |

这个最终表格的索引中包含您需要的所有信息,如果您愿意,您可以在最终系列上.reset_index() 生成一个包含 5 列的 DataFrame:id、length、width、material 和 final包含重复数的列。

【讨论】:

  • 非常感谢您帮助我!这与我需要的非常接近,但是我没有按 ID 分组(这是一个唯一的数字,而不仅仅是 1、2、3 等)我只对材料、长度和宽度进行分组。因此,我需要输出返回哪个 ID 属于该材质、长度和宽度。我几乎需要将原始问题中的输出过滤为“不止一行”,就像您在上面所做的那样。
猜你喜欢
  • 2020-09-15
  • 2021-02-24
  • 2013-05-30
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-05
  • 2022-07-08
相关资源
最近更新 更多