python数据帧上的平均值和最大值

2024-09-29 17:15:41 发布

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

是否可以在数据帧上同时执行最大和平均操作。我的目标是为Python中的以下数据创建一个条形图和线形图

  1. 查找得分最高的前3个国家{德国、加拿大、法国}
  2. 对于上述国家,请找到平均价格

酒吧将在最大点,而趋势线将在平均价格

import numpy as np

dfrn1 = pd.DataFrame({
    'country' : np.array(['France', 'US', 'France', 'US', 'Germany', 'US', 'France', 'France', 'India', 'Canada' ]),
    'price' : np.array([1,2,3,4,5,6,7,8,9,7]),
    'points' : np.array([98,88,90,90,100,69,87,87,87,99 ])
})

dfrn1

这就是我所拥有的

country = dfrn1.groupby("country")

country.describe().head()

t1 = country.points.max().sort_values(ascending=False).head(4).reset_index(name='points')
t2 = country.price.mean().reset_index(name='price') 

mergedStuff = pd.merge(t1, t2, on=['country'], how='inner')
mergedStuff

fig = go.Figure()

fig.add_trace(
    go.Bar(
        x= mergedStuff['country'],
        y= mergedStuff['points'],
        name="Maximum Points" ,
        marker=dict(color = '#47d2fc'),

    ))
fig.add_trace(
    go.Scatter(
        x= mergedStuff['country'],
        y= mergedStuff['price'],
        name="Average Price" ,
        line=go.scatter.Line(color="crimson"),
    ))        

fig.show()


Tags: 数据namegonpfig国家arraycountry
1条回答
网友
1楼 · 发布于 2024-09-29 17:15:41
temp = dfrn1['points'].nlargest(3)
df2 = pd.merge(dfrn1, temp).sort_values('points', ascending=False) # creates a dataframe of top 3 countries with maximum points sorted in descending order

df2
df2["price"].mean()

不是最有效的解决方案,但希望它能帮助你

相关问题 更多 >

    热门问题