使用 python for 循环将硬编码更改为更灵活

Change hardcode to more flexible using python for loop

我正在编写有关绘图的代码。我写的是hardcode方式,所以我的代码不够灵活。

我知道可以使用 for 循环 来解决 hardcode 问题。但是我Python能力不够强

这是我的代码。

df1 = df[df.cluster==0]
df2 = df[df.cluster==1]
df3 = df[df.cluster==2]

plt.scatter(df1.Age,df1['Income($)'],color='green')
plt.scatter(df2.Age,df2['Income($)'],color='red')
plt.scatter(df3.Age,df3['Income($)'],color='black')

在这种情况下有 3 个集群。如果 cluster = 4,则需要写更多。 df4 = ...

我可以写一个for循环吗,像这样

n = number of cluster
for i in range(n):
    df(random) = df[df.cluster==i]
for j in range(n):
    plt.scatter(df(n).Age,df(n)['Income($)'],color='RANDOM')

我的问题是只写几行代码而不是使用硬编码方式。

这是 pandas 中的经典 "groupby" 操作。

看看一些关于使用 groupby 的帖子。你可以...

  • 使用groupby根据簇的值进行分组
  • 使用 for 循环遍历组并...
  • 在组容器中绘制每个组。

这是一个使用 groupby

的例子
In [57]: from matplotlib import pyplot as plt                                   

In [58]: import pandas as pd                                                    

In [59]: data = {'year':[1976, 1979, 1982, 1978, 1982], 'income':[200, 170, 100,
    ...:  50, 120], 'cluster': [1, 1, 1, 2, 2]}                                 

In [60]: df = pd.DataFrame(data)                                                

In [61]: df                                                                     
Out[61]: 
   year  income  cluster
0  1976     200        1
1  1979     170        1
2  1982     100        1
3  1978      50        2
4  1982     120        2

In [62]: for label, df in df.groupby('cluster'): 
    ...:     plt.plot(df['year'], df['income'], label=label) 
    ...:                                                                        

In [63]: plt.legend()                                                           
Out[63]: <matplotlib.legend.Legend at 0x7fe792601e80>

In [64]: plt.show() 

产生:

一种可能:

colors = ['green', 'red', 'black']

for i in range(3):
    df_temp = df[df.cluster==i]
    plt.scatter(df_temp.Age, df_temp['Income($)'], color=colors[i])

如果您正在寻找一个简单的解决方案,也许就是这样。 (我已经重复使用了您的代码示例)

n = num_of_clusters
my_colors = ['green', 'red', 'black', ...]
for i in range(n):
    df_i = df[df.cluster == i]
    plt.scatter(df_i.Age, df_i['Income($)'], color=my_colors[i])