Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 9413

Groupby a df column based on 2 other columns

$
0
0

I have an df which has 3 columns lets say Region, Country and AREA_CODE.

Region      Country     AREA_CODE===================================AMER       US             A1AMER       CANADA         A1AMER       US             B1AMER       US             A1

I want to get the output like list of AREA_CODE for each country under each Region with 'ALL' as list value as well. something like

{"AMER": {"US": ["ALL", "A1", "B1"],"CANADA": ["ALL", "A1"]          }}

So far i have tried to groupby both region and country column and then tried to group & agg it by AREA_CODE, it is throwing error

df.drop_duplicates().groupby(["Region", "Country"]).groupby("Country")['AREA_CODE'].agg(lambda x: ["ALL"]+sorted(x.unique().tolist())).to_dict()

Could someone kindly help me with this.

Thanks,


Viewing all articles
Browse latest Browse all 9413

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>