Skip to content Skip to sidebar Skip to footer

How To Generate Dynamic Variable Names In Pandas Dataframe

I have one variable in python (value may change) a = 6 Now depending upon the values I have to generate 6 clusters from K-means clustering which gives me following labels in arr

Solution 1:

It is generally better practice to just use a dict() and, then make your 'dynamic variable names' keys to the dictionary instead. You could use:

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

You can then access the values in the dictionary using eg clusters['cluster_1'].

Solution 2:

I want to suggest you to store your clusters in a dictionary: And the code will be like:

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

Post a Comment for "How To Generate Dynamic Variable Names In Pandas Dataframe"