【问题标题】:How to take only the first 30 rows in plotly express python如何在plotly express python中只取前30行
【发布时间】:2021-05-22 19:08:36
【问题描述】:

我有一个 Excel 文件,其中有一列名为“产品”和“数量”。在 Product 列中,有超过 100 种不同的商品(衣服、鞋子、帽子、帽子等),而 Quantity 列显示了这些产品的销售量。

**Product**     **Quantity**
Shirt A             2
Shirt A             5
Shirt C             1
Shirt A             9
Shoes B             3

我想对所有不同的商品进行分组并计算它们的总数量,但仅针对最畅销的 25 种商品。在 pandas 中会是这样的:

df = pd.read_csv('directory\Sales.csv')

df_products = df[['Product', 
'Quantity']].groupby('Product').sum().head(25).sort_values(by='Quantity', ascending=False)

但是我怎样才能在 plotly.express 制作的直方图中做同样的事情呢?我试过这个:

fig_product = px.histogram(data_frame=df_products, x='Product', y='Quantity')

这向我显示了所有 +100 产品的名称及其销售数量,但我只想显示其中的前 25 个。我该怎么做?

【问题讨论】:

    标签: python pandas plotly


    【解决方案1】:

    一切都在数据帧准备中

    • groupby().sum() 获取所需的总数
    • sort_values().head() 要绘制的项目数。在这个例子中,我选择了前 10 名
    • 直方图和条形图没有区别
    import plotly.graph_objects as go
    import plotly.express as px
    
    df = pd.DataFrame({"product":np.random.choice(list("abcdefghijklmnonpqrstuvwxyz"), 200), "quantity":np.random.uniform(3,5,200)})
    
    df = df.groupby("product", as_index=False).sum().sort_values("quantity", ascending=False).head(10)
    
    go.Figure(go.Bar(x=df["product"], y=df["quantity"]))
    px.histogram(data_frame=df, x='product', y='quantity')
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2014-07-14
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多