【问题标题】:Pandas for loop on a group byPandas for 在组上循环
【发布时间】:2014-03-15 00:47:08
【问题描述】:

我有一个数据集,其中包含一个类别字段“城市”和 2 个指标,即年龄和体重。我想使用循环为每个城市绘制散点图。但是,我正在努力将我需要的 group by 和 loop 组合在一个语句中。如果我只使用一个 for 循环,我最终会为每条记录生成一个图表,如果我按分组进行分组,我会得到正确数量的图表,但没有值。

这是我的代码,只使用了我的组的 for 循环,被注释掉了:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt


d = {  'City': pd.Series(['London','New York', 'New York', 'London', 'Paris',
                        'Paris','New York', 'New York', 'London','Paris']),
       'Age' : pd.Series([36., 42., 6., 66., 38.,18.,22.,43.,34.,54]),
     'Weight': pd.Series([225,454,345,355,234,198,400, 256,323,310])
}

df = pd.DataFrame(d)

#for C in df.groupby('City'):
for C in df.City:
    fig = plt.figure(figsize=(5, 4))
    # Create an Axes object.
    ax = fig.add_subplot(1,1,1) # one row, one column, first plot
    # Plot the data.
    ax.scatter(df.Age,df.Weight, df.City == C, color="red", marker="^")

【问题讨论】:

    标签: python pandas for-loop matplotlib pandas-groupby


    【解决方案1】:

    不要多次调用plt.figure,因为每次调用都会创建一个新图形(粗略地说,窗口)。

    import pandas as pd
    import numpy as np
    import matplotlib.pylab as plt
    
    d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
                            'Paris', 'New York', 'New York', 'London', 'Paris'],
         'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
         'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}
    
    df = pd.DataFrame(d)
    fig, ax = plt.subplots(figsize=(5, 4))    # 1
    df.groupby(['City']).plot(kind='scatter', x='Age', y='Weight', 
                              ax=ax,          # 2
                              color=['red', 'blue', 'green'])
    
    plt.show()
    

    1. plt.subplots 返回一个图形 fig 和一个坐标区 ax
    2. 如果你将ax=ax 传递给 Panda 的 plot 方法,那么所有的 plot 都会 显示在同一轴上。

    为每个城市制作一个单独的数字:

    import pandas as pd
    import numpy as np
    import matplotlib.pylab as plt
    
    d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
                            'Paris', 'New York', 'New York', 'London', 'Paris'],
         'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
         'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}
    
    df = pd.DataFrame(d)
    groups = df.groupby(['City'])
    for city, grp in groups:                           # 1
        fig, ax = plt.subplots(figsize=(5, 4))
        grp.plot(kind='scatter', x='Age', y='Weight',  # 2
                 ax=ax)               
    
        plt.show()
    
    1. 这也许就是你所缺少的。当你迭代一个 GroupBy 对象,它返回一个 2 元组:groupby 键和 子数据框。
    2. 在 for 循环中使用 grp,子 DataFrame 而不是 df

    【讨论】:

    • 所以在某些情况下,这将是一个很好的解决方案,但在我的情况下,当我说我想要每个城市的散点图时,我实际上是指每个城市的单独图表/数字。原因是完整的数据集要大得多,因此我需要查看不同图表上的不同点。
    • 不知道为什么,但是上面的 2 个例子抛出了错误:ValueError: Invalid chart type given scatter 当我运行它们时。我已经按照你的建议进行了分组并插入到我的代码中,这样我现在就可以得到我正在寻找的输出了。会对为什么我会在您的结构中看到无效的图表类型错误感兴趣。自己没弄明白。
    • kind='scatter'added in Pandas v.0.13.0
    • 哦,是的,已经更新了库,现在可以使用了。谢谢。
    • 不确定这是否值得提出一个新问题,但第一个示例似乎不再适用于 pandas 0.17.1 版和 matplotlib 1.5.0 版。相反,它使用折线图而不是散点图生成 4 个单独的数字。我找不到与这些版本一起使用的替代方案来生成一个包含多个组的单个图形。
    【解决方案2】:

    我使用了另一篇文章中的 group by 并插入到我的代码中为每个 group by 生成图表:

    import pandas as pd
    import numpy as np
    import matplotlib.pylab as plt
    
    
    d = {  'City': pd.Series(['London','New York', 'New York', 'London','Paris',
                            'Paris','New York', 'New York', 'London','Paris']),
           'Age' : pd.Series([36., 42., 6., 66., 38.,18.,22.,43.,34.,54]) ,
         'Weight': pd.Series([225,454,345,355,234,198,400, 256,323,310])
    
    }
    
    df = pd.DataFrame(d)
    
    groups = df.groupby(['City'])
    for city, grp in groups: 
        fig = plt.figure(figsize=(5, 4))
        # Create an Axes object.
        ax = fig.add_subplot(1,1,1) # one row, one column, first plot
        # Plot the data.
        ax.scatter(df.Age,df.Weight, df.City == city, color="red", marker="^")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-13
      • 2014-01-29
      • 1970-01-01
      • 2020-03-16
      • 2018-12-15
      • 2020-02-08
      • 2016-08-28
      • 2021-10-02
      相关资源
      最近更新 更多