I have a dataframe column as:
df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9]})
My output list needed is (keeping the min max values of ranges):
[[1,4],[5,7],[8,9]]
Here's how far I got:
import pandas as pd
df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9]})
# Convert df column to a unique value list and sort ascending
us = df['a'].unique().tolist()
us.sort()
lst1 = [int(v) for v in us]
# Create 3 groups of values
lst2 = [lst1[i:i + 3] for i in xrange(0, len(lst1), 3)]
# Keep only min and max of these groups
How do I convert this:
[[1,3,4],[5,6,7],[8,9]]
to my desired output?
You can use a list comprehension for this:
lst3 = [[min(i), max(i)] for i in lst2]
You can use dataframe
df = df.sort_values("a").drop_duplicates().reset_index(drop=True)
df.groupby(df.index // 3).agg(['min', 'max']).values.tolist()
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.