Python groupby 和 count 显示在图上
Python groupby and count to show on the plot
请帮助正确书写。在图片上,我有一个 table,其中包含“团队”和“积分”。我想计算每个 F1 Team 收集了多少分以显示在情节上。我试着这样做:
team_points= cons.groupby('Team')['Points'].count()
team_points = pd.DataFrame(team_points)
team_points.columns = ['Points']
team_points.reset_index(level=0, inplace=True)
team_points.sort_values(by=['Points'], inplace=True,
ascending=False)
team_points = team_points.head(10)
team_points = team_points[::-1]
fig = px.bar(team_points, x='Team',
y='Points',color='Points',width=750, height=500)
fig.update_layout(title={'text': 'Teams with The Most Championships
Won','y':0.95,'x':0.5})
fig.show()
Table
你的pandas代码做的事情很奇怪
- 确保 points 是数字
groupby().agg()
得到总数
- 已筛选出超过 100 分的团队以限制条数
- plotly 代码那么简单
import plotly.express as px
import requests
import pandas as pd
res = requests.get("http://ergast.com/api/f1/constructorStandings.json", params={"limit":1000})
df = (pd.DataFrame(res.json()["MRData"]["StandingsTable"]["StandingsLists"])
.explode("ConstructorStandings").reset_index(drop=True)
.pipe(lambda d: d.loc[:,["season","round"]].join(d["ConstructorStandings"].apply(pd.Series)))
.pipe(lambda d: d.join(d["Constructor"].apply(pd.Series))).drop(columns="Constructor")
)
df["points"] = pd.to_numeric(df["points"])
dfp = df.groupby(["name"]).agg({"points":"sum"}).loc[lambda d: d["points"].gt(100)]
px.bar(dfp, x=dfp.index, y="points", color="points")
请帮助正确书写。在图片上,我有一个 table,其中包含“团队”和“积分”。我想计算每个 F1 Team 收集了多少分以显示在情节上。我试着这样做:
team_points= cons.groupby('Team')['Points'].count()
team_points = pd.DataFrame(team_points)
team_points.columns = ['Points']
team_points.reset_index(level=0, inplace=True)
team_points.sort_values(by=['Points'], inplace=True,
ascending=False)
team_points = team_points.head(10)
team_points = team_points[::-1]
fig = px.bar(team_points, x='Team',
y='Points',color='Points',width=750, height=500)
fig.update_layout(title={'text': 'Teams with The Most Championships
Won','y':0.95,'x':0.5})
fig.show()
Table
你的pandas代码做的事情很奇怪
- 确保 points 是数字
groupby().agg()
得到总数- 已筛选出超过 100 分的团队以限制条数
- plotly 代码那么简单
import plotly.express as px
import requests
import pandas as pd
res = requests.get("http://ergast.com/api/f1/constructorStandings.json", params={"limit":1000})
df = (pd.DataFrame(res.json()["MRData"]["StandingsTable"]["StandingsLists"])
.explode("ConstructorStandings").reset_index(drop=True)
.pipe(lambda d: d.loc[:,["season","round"]].join(d["ConstructorStandings"].apply(pd.Series)))
.pipe(lambda d: d.join(d["Constructor"].apply(pd.Series))).drop(columns="Constructor")
)
df["points"] = pd.to_numeric(df["points"])
dfp = df.groupby(["name"]).agg({"points":"sum"}).loc[lambda d: d["points"].gt(100)]
px.bar(dfp, x=dfp.index, y="points", color="points")