【发布时间】:2020-06-08 05:50:00
【问题描述】:
我正在做一个关于酒精消费的 Pandas 项目。供您参考,数据集包含以下列:
|大陆 |国家 |啤酒 |精神 |葡萄酒 |
以下是我的代码:
# Separating data by continent
# ----------------------------
data_asia = data[data['Continent'] == 'Asia']
data_africa = data[data['Continent'] == 'Africa']
data_europe = data[data['Continent'] == 'Europe']
data_north = data[data['Continent'] == 'North America']
data_south = data[data['Continent'] == 'South America']
data_ocean = data[data['Continent'] == 'Oceania']
# Calculating n-largest for each category of drink
# ------------------------------------------------
top_5_asia_beer = data.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_asia_spir = data.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_asia_wine = data.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_asia_pure = data.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_africa_beer = data.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_africa_spir = data.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_africa_wine = data.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_africa_pure = data.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_europe_beer = data.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_europe_spir = data.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_europe_wine = data.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_europe_pure = data.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_north_beer = data.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_north_spir = data.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_north_wine = data.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_north_pure = data.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_south_beer = data.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_south_spir = data.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_south_wine = data.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_south_pure = data.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_ocean_beer = data.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_ocean_spir = data.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_ocean_wine = data.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_ocean_pure = data.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
我理解我的代码在重复性和重复性方面的荒谬性。谁能分享重构代码的技巧和窍门?
【问题讨论】:
-
尝试将其发布到codereview
-
groupby 然后 nlargest
标签: python python-3.x pandas refactoring data-science