Hello i have a list of the sort:
lst = [0.0000,0.0542,0.0899,0.7999,0.9999,1.8754]
The list keeps going.
Is there any way i can group the by one? Like for example every value that is between 0 to 1, and 1 to 2 etc.
As Id like to reppresent it on matplotlib of the count of numbers per group.
I tried everything but no success.
There is a nice library named itertools
which has a function called groupby
which can help you here. It collects adjacent values in a list together based on a predicate.
from itertools import groupby
lst = [0.0000,0.0542,0.0899,0.7999,0.9999,1.8754]
grouped_lst = [list(g) for k,g in groupby(lst, lambda x:int(x))]
Output:
[[0.0, 0.0542, 0.0899, 0.7999, 0.9999], [1.8754]]
lambda x:int(x)
is the predicate here. int
will convert your values to an integer ie remove the decimal point. You can then loop over these 'groups' and convert them to a list using list(g)
.
Note this method will only work if your list is sorted. Please sort your list beforehand if it may not be sorted.
You can use numpy
and numpy_indexed
:
import numpy as np
import numpy_indexed as npi
lst = [0.0000,0.0542,0.0899,0.7999,0.9999,1.8754]
npi.group_by(np.trunc(lst), lst)
Output
(array([0., 1.]),
[array([0. , 0.0542, 0.0899, 0.7999, 0.9999]), array([1.8754])])
#keys and groups
You can easily install the library with:
> pip install numpy-indexed
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.