如何在pandas datafram中生成动态变量名

2024-05-23 18:11:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个变量(值可能会改变)

a = 6

现在根据值,我必须从K-means clustering生成6个集群 它给了我数组中的下列标签

y_km
Out[36]: array([2, 5, 5, 2, 5, 0, 0, 1, 1, 4, 3, 4, 1, 0, 2, 2])

cluster_0 = np.where(y_km == 0)
cluster_1 = np.where(y_km == 1)
cluster_2 = np.where(y_km == 2)
cluster_3 = np.where(y_km == 3)
cluster_4 = np.where(y_km == 4)
cluster_5 = np.where(y_km == 5)

然后将数组中每个标签的位置存储到不同的变量中。我希望自动化这个过程,这样就不必显式地为变量名编写代码(cluster_0,cluster_1,cluster_2...)

for i in range(a):
    cluster_'%d'%i = np.where(y_km == i)

我在上面做,但这给了我语法错误。 然后我在数据帧中定义一列tsp_data_unique

tsp_data_unique['Clusters'] = 'Null'

然后,我正在执行以下操作以在dataframe中分配相应的集群标签。

tsp_data_unique['Clusters'].iloc[cluster_0] = 'Cluster 1'
tsp_data_unique['Clusters'].iloc[cluster_1] = 'Cluster 2'
tsp_data_unique['Clusters'].iloc[cluster_2] = 'Cluster 3'
tsp_data_unique['Clusters'].iloc[cluster_3] = 'Cluster 4'
tsp_data_unique['Clusters'].iloc[cluster_4] = 'Cluster 5'
tsp_data_unique['Clusters'].iloc[cluster_5] = 'Cluster 6'

我能把上面的过程自动化吗。


Tags: data过程np集群标签数组wheremeans
2条回答

我建议您将集群存储在字典中: 代码如下:

clusters = dict()
for i in range(a):
    clusters[i] = np.where(y_km == i)

通常最好使用dict(),然后将“动态变量名”键改为使用字典。您可以使用:

clusters = {}
for i in range(a):
    clusters['cluster_{}'.format(i)] = np.where(y_km == i)

然后可以使用egclusters['cluster_1']访问字典中的值。

相关问题 更多 >