我有一个数据集,它有一个类别字段“城市”和 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="^")