Home > Mobile >  Calculate frequency of float values in list Python
Calculate frequency of float values in list Python

Time:11-03

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]

CodePudding user response:

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]

CodePudding user response:

Below are different ways to get the frequency of elements from a list

Numpy

import numpy as np

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

values, freq = np.unique(np.array(values), return_counts=True)
print(values)
print(freq)

# Output
# [21.963  23.4131 23.7639 24.3934 24.5237 25.2829 25.394 ]
# [1 1 1 1 1 1 1]

Pandas

import pandas as pd

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

freq = pd.DataFrame(values).value_counts().values
print(values)
print(freq)

# Output
# [21.963  23.4131 23.7639 24.3934 24.5237 25.2829 25.394 ]
# [1 1 1 1 1 1 1]
  • Related