熊猫循环上一组

时间:2014-02-15 16:05:07

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

我有一个数据集,其中包含一个类别字段,“城市”和2个指标,年龄和权重。我想使用循环为每个城市绘制一个散点图。但是我正努力在单个语句中将我需要的group by循环组合起来。如果我只使用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="^")

2 个答案:

答案 0 :(得分:2)

不要多次拨打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()

enter image description here

  1. plt.subplots返回一个数字fig和一个轴ax
  2. 如果你将ax=ax传递给Panda的情节方法,那么所有的情节都会如此 如何在同一轴上。

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

    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-loop中使用grp,子数据框而不是df

答案 1 :(得分:2)

我在另一篇文章中使用了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="^")
相关问题