【发布时间】:2020-02-21 08:38:55
【问题描述】:
我真的是 python 新手,只是想进行一些基本练习。我今天开始创建基本函数,并想做一个与 this project here. 类似的项目
我想使用不同的数据集 (a superbowl data set) 来执行与上面链接的项目相同的代码。我想使用相同的代码来计算球队赢得超级碗的次数。我的代码可以正常工作,但现在我对绘制这些数据感到好奇。我对大多数图表都使用 matplotlib.pyplot,但这不起作用,因为我使用的是数据字典。我如何绘制这些数据,也许在一个轴上是团队,在另一个轴上是他们的胜利?代码如下:
# Import pandas
import pandas as pd
# Import Twitter data as DataFrame: df
df = pd.read_csv("https://raw.githubusercontent.com/veeralakrishna/DataCamp-Portfolio-Project-Solutions--Python/master/TV%2C%20Halftime%20Shows%2C%20and%20the%20Big%20Game/datasets/super_bowls.csv")
# Define count_entries()
def count_winners(df, col_name='team_winner'):
"""Return a dictionary with counts of
wins as value for each team."""
# Initialize an empty dictionary: cols_count
wins_count = {}
# Extract column from DataFrame: col
col = df[col_name]
# Iterate over the column in DataFrame
for entry in col:
# If entry is in wins_count, add 1
if entry in wins_count.keys():
wins_count[entry] += 1
# Else add the entry to wins_count, set the value to 1
else:
wins_count[entry] = 1
# Return the cols_count dictionary
return wins_count
这将返回我要绘制的字典:
{'Philadelphia Eagles': 1, 'New England Patriots': 5, 'Denver Broncos': 3, 'Seattle Seahawks': 1, 'Baltimore Ravens': 2, 'New York Giants': 4, 'Green Bay Packers': 4, 'New Orleans Saints': 1, 'Pittsburgh Steelers': 6, 'Indianapolis Colts': 1, 'Tampa Bay Buccaneers': 1, 'St. Louis Rams': 1, 'Dallas Cowboys': 5, 'San Francisco 49ers': 5, 'Washington Redskins': 3, 'Chicago Bears': 1, 'Los Angeles Raiders': 1, 'Oakland Raiders': 2, 'Miami Dolphins': 2, 'Baltimore Colts': 1, 'Kansas City Chiefs': 1, 'New York Jets': 1}
任何建议将不胜感激!
【问题讨论】:
标签: python dictionary graph