python – 从pandas系列列表中获取唯一值
作者:互联网
我在DataFrame中有一个包含类别列表的列.例如:
0 [Pizza]
1 [Mexican, Bars, Nightlife]
2 [American, New, Barbeque]
3 [Thai]
4 [Desserts, Asian, Fusion, Mexican, Hawaiian, F...
6 [Thai, Barbeque]
7 [Asian, Fusion, Korean, Mexican]
8 [Barbeque, Bars, Pubs, American, Traditional, ...
9 [Diners, Burgers, Breakfast, Brunch]
11 [Pakistani, Halal, Indian]
我试图做两件事:
1)获取唯一类别 – 我的方法是空集,迭代序列并附加每个列表.
我的代码:
unique_categories = {'Pizza'}
for lst in restaurant_review_df['categories_arr']:
unique_categories = unique_categories | set(lst)
这为我提供了列中所有列表中包含的一组唯一类别.
2)生成类别计数的饼图,每个餐馆可以属于多个类别.例如:餐厅11属于巴基斯坦,印度和清真类别.我的方法是再次遍历类别,再通过一系列迭代来获得计数.
这样做有简单或优雅的方法吗?
提前致谢.
解决方法:
IIUC:
尝试:
df['category'].apply(pd.Series).stack().value_counts()
输出:
Mexican 3
Barbeque 3
Thai 2
Fusion 2
American 2
Bars 2
Asian 2
Pubs 1
Burgers 1
Traditional 1
Brunch 1
Indian 1
Korean 1
Halal 1
Pakistani 1
Hawaiian 1
Diners 1
Pizza 1
Nightlife 1
New 1
Desserts 1
Breakfast 1
dtype: int64
随着绘图:
df['category'].apply(pd.Series).stack().value_counts().plot.pie()
Per @ coldspeed的评论
from itertools import chain
from collections import Counter
pd.DataFrame.from_dict(Counter(chain(*df['category'])), orient='index').sort_values(0, ascending=False)
输出:
Barbeque 3
Mexican 3
Bars 2
American 2
Thai 2
Asian 2
Fusion 2
Pizza 1
Diners 1
Halal 1
Pakistani 1
Brunch 1
Breakfast 1
Burgers 1
Hawaiian 1
Traditional 1
Pubs 1
Korean 1
Desserts 1
New 1
Nightlife 1
Indian 1
标签:python,pandas,unique,set,pie-chart 来源: https://codeday.me/bug/20190828/1746560.html