我正在做一个关于酒精消费的项目。请参考,数据集包含以下列:
|大陆|国家|啤酒|白酒|葡萄酒|
以下是我的代码:
# 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']]
我理解我的代码在重复和重复方面的荒谬性。任何人都可以分享重构代码的技巧吗
其中一种方法是:
相关问题 更多 >
编程相关推荐