Pandas:基于条件的列的唯一值

时间:2021-03-04 09:07:25

标签: python pandas

我在数据框中有两列:fueltype 和 number of door.Fueltype 有 3 类:Petrol、Diesel 和 CNG。如何找到汽油燃料类型中门数的唯一值?

1 个答案:

答案 0 :(得分:0)

假设您的数据框如下所示:

   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