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

问题描述 投票:0回答:1

是否有可能在一个数据帧上同时执行最大和均值运算。我的目标是为在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()

python dataframe group-by max mean
1个回答
0
投票
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()

不是最有效的解决方案,希望对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.