Search code examples
pythonpandasdataframefrequency

Calculate frequency of float values in list Python


I need to calculate frequency of float elements in list. Convert them to int I can't, because I need to manipulate then float values, not int.

My try in the code below:

    values = [21.963, 23.4131, 23.7639, 24.3934, 24.5237, 25.2829, 25.394]
    df = pd.Series(values).value_counts().sort_index().reset_index().reset_index(drop=True)
    df.columns = ['Element', 'Frequency']
    frequency = (df['Frequency'].values).tolist() 

hovewer I want to have two separate lists(not dataframe):

  1. List of float elements
  2. List of frequencies of float elements given

Expected output:

values = [21.963, 23.4131, 23.7639, 24.3934, 24.5237, 25.2829, 25.394]

frequency = [1, 1, 1, 1, 1, 1, 1]


Solution

  • from collections import Counter
    
    Counter(values)
    
    Output:
    Counter({21.963: 1,
             23.4131: 1,
             23.7639: 1,
             24.3934: 1,
             24.5237: 1,
             25.2829: 1,
             25.394: 1})
    
    list2 = list(Counter(values).values())
    list2
    Output:
    
    [1, 1, 1, 1, 1, 1, 1]