Sort data in dataframe pandas by repeating frequency of each element

Asked

Viewed 24 times

0

I have a dataframe and I want to organize the data by the frequency of appearance of each element. From the most repeated to the least repeated, to create a ranking. I want the organization to be made from the columns uf and tipo_acidente

acidentes2020 = pd.read_csv('https://arquivos.prf.gov.br/arquivos/index.php/s/jdDLrQIf33xXSCe/download', compression='zip',encoding='iso8859-1', sep=';')

ranking2020 = acidentes2020[['uf', 'tipo_acidente']]
  • 1

    do you just want to draw the notes? If yes, see the method sort_values: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html. If you want to group the values before ranking, use groupby: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html

  • sorry, my question was mistaken. I really want to rank. For example: I want you to show the tipo_acidente that most occurred for determined uf.

1 answer

1

In detail:

Loading library

import pandas as pd

Creating Dataframe for Testing

df = pd.DataFrame({"A": [1,2,3,1,2,3,1,1,2,2,1,3]})

print(df)

    A
0   1
1   2
2   3
3   1
4   2
5   3
6   1
7   1
8   2
9   2
10  1
11  3

Creating column with frequencies

df['frequencia'] = df.groupby('A')['A'].transform('count')

print(df)

    A  frequencia
0   1           5
1   2           4
2   3           3
3   1           5
4   2           4
5   3           3
6   1           5
7   1           5
8   2           4
9   2           4
10  1           5
11  3           3

Ordering by frequency

df1 = df.sort_values(by='frequencia')

print(df1)

    A  frequencia
2   3           3
5   3           3
11  3           3
1   2           4
4   2           4
8   2           4
9   2           4
0   1           5
3   1           5
6   1           5
7   1           5
10  1           5

Note 1: use the ascending=False to order in descending order

Note 2: use the inplace=True not having to assign the result to another Dataframe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.