【发布时间】:2022-01-20 19:21:59
【问题描述】:
我有一个熊猫数据框。我想计算一列中的所有值,以了解其中哪些是重复的。然后,我想只提取重复的值,我想用它们来创建一个子数据框。
举个例子吧。说这是我的数据框:
df =
type color name
0 fruit red apple
1 fruit yellow banana
2 meat brown steak
3 fruit green apple
4 fruit orange orange
5 veg orange carrot
6 fruit yellow apple
7 meat brown steak
8 veg orange carrot
我想知道“名称”列中是否有任何重复值。为此,我使用这行代码:
df['name'].value_counts().loc[lambda x : x>1]
这就是我得到的:
apple 3
steak 2
carrot 2
然后,我想创建一个子数据框,用“apple”、“steak”、“carrot”过滤“name”列,以找到与另一列相关的值。当然,这可以通过适当的函数来完成。
想要的输出是:
sub_df =
type color name
0 fruit red apple
1 fruit green apple
2 fruit yellow apple
3 meat steak brown
4 meat steak brown
5 veg orange carrot
6 veg orange carrot
我尝试了不同类型的代码,但没有成功。我认为问题出在 df.count_values() 的使用上,因为它给了我一个带有出现次数的 Pandas 系列,而无法访问该方法计数的值。
有什么建议吗?
【问题讨论】:
标签: python pandas distinct-values