【问题标题】:Python/Pandas/Matplotlib - Iterating/Looping Through Charts - Duplicate Charts IssuePython/Pandas/Matplotlib - 通过图表迭代/循环 - 重复图表问题
【发布时间】:2019-05-28 15:54:34
【问题描述】:

尝试为每个“查询”生成一个图表,其中 x 轴为“关键字”,y 轴为“趋势”值。

这是我的数据框,名为 'df'。

                   query    keyword                     trend   sequence
1592    womens underwear    women's underwear on sale   1.40    1
1593    womens underwear    sale on womens underwear    1.40    2
1594    womens underwear    women's underwear for sale  1.40    3
1595    womens underwear    womens underwear sale       1.40    4
3687    womens underwear    womens underwear sale       1.40    5
3802    womens bra          lingerie sleepwear          124.00  1
1705    womens bra          women's n i t bracket       3.00    2
3852    womens bra          best bras for women         2.22    3
3826    womens bra          fantasy bra                 1.75    4
3851    womens bra          32 c bra                    1.71    5

发生的情况是,我在 for 循环中为每个查询生成了 'n' 个图表。许多重复!

for i in df['query']:
   loopChart = df[df['query']==i]
   plt.figure(figsize=(10,4))
   plt.bar(loopChart['keyword'], loopChart['trend'])
   plt.title(i)
   plt.xticks(rotation=90)
   plt.show()

我在这里尝试了一些没有运气的事情:

1) 创建一个序列字段(在我的 DF 示例中)并使用它来限制我的 loopChart 行中的输出

loopChart = df[df['query']==i & df['sequence']==1]

2) 使用我的序列字段作为嵌套的 while 循环条件

for i in df['query']:

while df['sequence']

对于我还可以如何应对这一挑战有任何见解吗?试图想办法只检查每个“查询”并绘制一次图表,但被难住了。

我的最终结果应该只是两个条形图,但现在是 10 个。

【问题讨论】:

    标签: python pandas for-loop matplotlib


    【解决方案1】:

    忽略 - 我用一小段代码解决了这个问题...在我的 for 循环头中添加了一个 .unique() ,一切都解决了。

    for i in df['query'].unique():
       loopChart = df[df['query']==i]
       plt.figure(figsize=(10,4))
       plt.bar(loopChart['keyword'], loopChart['trend'])
       plt.title(i)
       plt.xticks(rotation=90)
       plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多