我有一个ID的Pandas DataFrame,我将其按5列分组。
希望获得仅包含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
非常新的编码,所以非常感谢任何帮助!
根据我的理解,您有一个数据集:
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、长度、宽度、材质和包含重复数的最终列。