[英]Pandas:Unique values of a column based on a condition
我在 dataframe 中有兩列:燃料類型和門數。燃料類型有 3 個類別:汽油、柴油和 CNG。如何找到汽油燃料類型中門數的唯一值?
假設您的 dataframe 如下所示:
fueltype number of doors
0 Petrol 2
1 Petrol 4
2 Petrol 4
3 Petrol 4
4 Diesel 2
5 Diesel 2
6 Diesel 4
7 Diesel 4
8 Diesel 4
9 Diesel 4
10 CNG 2
11 CNG 2
12 CNG 4
13 CNG 2
14 CNG 4
那么這個:
group = df.groupby('fueltype')
df2 = group.apply(lambda x: x['number of doors'].unique())
為您提供每種燃料的獨特價值
fueltype
CNG [2, 4]
Diesel [2, 4]
Petrol [2, 4]
dtype: object
編輯
如果您想要每種燃料類型的所有唯一值:
df2.explode()
將返回
fueltype
CNG 2
CNG 4
Diesel 2
Diesel 4
Petrol 2
Petrol 4
dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.