要在绘图上显示的Python groupby和count

2024-05-15 08:58:04 发布

您现在位置:Python中文网/ 问答频道 /正文

请请求帮助正确书写此内容。在这张照片上,我有一张有“团队”和“积分”的桌子。我想数一数每一个F1车队已经收集了多少分,以显示它的阴谋。我试着这样做:

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()

桌子

enter image description here


Tags: true内容fig团队照片teampointsf1
1条回答
网友
1楼 · 发布于 2024-05-15 08:58:04

您的pandas代码正在做一些非常奇怪的事情

  • 确保为数字
  • groupby().agg()以获取总数
  • 已筛选到得分超过100分的团队,以限制条数
  • 那么代码就很简单了
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")

enter image description here

相关问题 更多 >