Retrieve most frequent value for each couple of values

Viewed 95

I'm working with a df having 3 columns: 'Latitude', 'Longitude' and 'street_type'.

The 'street_type' column has multiple values like 'rectilinear', 'roundabout' exc.

I would like to retrieve the most frequent value for each couple of values 'Latitude' and 'Longitude'.

I tried using the group by expression like this one:

df=df.group_by(['Latitude','Longitude'])[['steet_type']].sum().reset_index()

It returns me the df with the group by but I would like to have the most frequent value with its count and the coordinate for that value.

The street_type column has only strings si I used the get_dummies method to have only numbers. Was it a good practice or not for the groupby() and a sum()?

Thank you in advance!

data = {'Latitude'=[-41.794,-41.733,-41.335,-41.794],'Longitude'=[-12.344,-12.456,-12.929,-12.344],'street_type'={'rectilinear','roundabout','intersection','rectilinear']}

df = pd.DataFrame(data)
df = pd.get_dummies(df, columns=['street_type'])
df = df.groupby(['Latitude','Longitude'])[['street_type_rectilinear','street_type_roundabout','street_type_intersection']].sum().reset_index()

The output from groupby snd sum()

Latitude Longitude street_type_rectilinear street_type_roundabout street_type_intersection
-41.794 -12.344 1 0 0
-41.733 -12.456 0 1 0
-41.335 -12.929 0 0 1
-41.794 -12.344 1 0 0

same result for agg(pd.Series.mode) same result for agg(lambda x: x.mode().iat[0]).reset_index()

The desidered output is:

Latitude Longitude street_type_rectilinear street_type_roundabout street_type_intersection
-41.794 -12.344 2 0 0
-41.733 -12.456 0 1 0
-41.335 -12.929 0 0 1
-41.794 -12.344 2 0 0

EDITED THE QUESTION WITH SAMPLE CODE

2 Answers

Try with agg and pd.Series.mode:

print(df.groupby(['Latitude', 'Longitude'])['street_type'].agg(pd.Series.mode).reset_index())

Output:

   Latitude  Longitude   street_type
0   -41.794    -12.344   rectilinear
1   -41.733    -12.456    roundabout
2   -41.335    -12.929  intersection

Use custom lambda function for first mode:

df = (df.groupby(['Latitude', 'Longitude'])['street_type']
        .agg(lambda x: x.mode().iat[0])
        .reset_index())
Related