基于Country列唯一值统计Car列元素的名称与数量
解决方案
先把你的示例DataFrame用代码还原出来:
import pandas as pd data = { 'Car': ['BMW', 'Tesla', 'BMW', 'Mercedes', 'Tesla'], 'Country': ['Germany', 'USA', 'Germany', 'France', 'USA'] } df = pd.DataFrame(data)
不用纠结透视表了,用groupby+value_counts直接搞定,完全匹配你的输出需求:
直接输出指定格式
# 按国家分组,统计每个国家下各车型的数量 country_car_stats = df.groupby('Country')['Car'].value_counts() # 遍历统计结果,按要求打印 for (country, car), count in country_car_stats.items(): print(f"{country}:") print(f"{car} - {count}\n")
运行后输出就是你要的样子:
Germany: BMW - 2 USA: Tesla - 2 France: Mercedes - 1
要是需要结构化存储结果
如果还要把统计结果存成字典方便后续用,这么写:
# 转成以国家为键,车型-数量为值的字典 result_dict = df.groupby('Country')['Car'].value_counts().unstack(fill_value=0).to_dict('index') # 同样按格式输出 for country, car_counts in result_dict.items(): print(f"{country}:") for car, cnt in car_counts.items(): if cnt > 0: print(f"{car} - {cnt}\n")
至于你说的透视表不好用,是因为透视表会把所有出现过的车型都列出来(哪怕某个国家没有该车型也会显示0),而上面的方法只会保留每个国家实际存在的车型,更贴合你的需求。
内容的提问来源于stack exchange,提问作者Mamed
相关产品推荐
相关产品推荐

