python-一组循环的熊猫
作者:互联网
我有一个具有类别字段“城市”和2个指标(年龄和体重)的数据集.我想使用循环为每个城市绘制散点图.但是,我很难在单个语句中组合所需的分组依据和循环.如果仅使用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="^")
解决方法:
不要多次调用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()
> plt.subplots返回图形,无花果和坐标轴,ax.
>如果将ax = ax传递给Panda的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()
>也许这就是您所缺少的.当您遍历一个
GroupBy对象,它返回一个2元组:groupby键和
子DataFrame.
>在循环中使用grp(而不是df)作为子DataFrame.
标签:pandas-groupby,pandas,for-loop,matplotlib,python 来源: https://codeday.me/bug/20191029/1963417.html