Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert [('US', 144), ('CA', 37)] to ['US', 'CA']

I have a df with customer and country data. I want to count the countries so can find the top5 countries, and them use that as a filter elsewhere.

this gives me the counts

countries = collections.Counter(responses_2021['country'].dropna())

that yields this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[('US', 144), ('CA', 37), ('GB', 15), ('FR', 15), ('AU', 12)]

and this gives me the top 5

countries_top5 = countries.most_common(5)

now I need to transform it into a more simple structure so I can do my filter (here i’m just typing it manually because that’s the only way I could move forward lol)

options = ['US', 'CA', 'GB', 'FR', 'AU'] 
rslt_df = df[df['country'].isin(options)] 

So, to get from the this

[('US', 144), ('CA', 37), ('GB', 15), ('FR', 15), ('AU', 12)]

to this

['US', 'CA', 'GB', 'FR', 'AU'] 

I started by trying to remove the counts

countries_top5_names = np.delete(countries_top5, 1, 1)

but that yields

[['US'], ['CA'], ['GB'], ['FR'], ['AU']] 

so now I’m trying to flatten that, but I don’t know how.

better way?

SOLUTION (thanks to @dan04 below)

countries_top5_names = [x[0] for x in countries_top5] 
rslt_df = df[df['country'].isin(countries_top5_names)] 

>Solution :

Just take element [0] of each tuple.

>>> data = [('US', 144), ('CA', 37), ('GB', 15), ('FR', 15), ('AU', 12)]
>>> countries = [x[0] for x in data]
>>> countries
['US', 'CA', 'GB', 'FR', 'AU']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading