Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

How can i solve the index out of range error of python?

I'm new in python and im trying to work with an existent code for my work, im gettint an error of index, that i cant understand, ia have tried mutltiples option that i already seen but im still have the same problem, can anyone help me, please?

This is the code:

Repo = []
for p in Y:
    Repo.append((p/SUM_Y)**(0))#LABEL_WEIGHT[hoja]))

distributions = [
    ['Data after standard scaling',
    pd.DataFrame(StandardScaler().fit_transform(X),columns = ['x','y'])],
    ['Data after min-max scaling',
                pd.DataFrame(MinMaxScaler().fit_transform(X),columns = ['x','y'])],
    ['Data after max-abs scaling',
                pd.DataFrame(MaxAbsScaler().fit_transform(X),columns = ['x','y'])],
    ['Data after robust scaling',
                pd.DataFrame(RobustScaler(quantile_range=(25, 75)).fit_transform(X),columns = ['x','y'])],
    ['Data after power transformation (Yeo-Johnson)',
            pd.DataFrame(PowerTransformer(method='yeo-johnson').fit_transform(X),columns = ['x','y'])],
    ['Data after power transformation (Box-Cox)',
            pd.DataFrame(PowerTransformer(method='box-cox').fit_transform(X),columns = ['x','y'])],
    ['Data after quantile transformation (gaussian pdf)',
            pd.DataFrame(QuantileTransformer(output_distribution='normal')
            .fit_transform(X),columns = ['x','y'])],
    ['Data after quantile transformation (uniform pdf)',
            pd.DataFrame(QuantileTransformer(output_distribution='uniform')
            .fit_transform(X),columns = ['x','y'])],
    ['Data after sample-wise L2 normalizing',
            pd.DataFrame(Normalizer().fit_transform(X),columns = ['x','y'])],
]


for j in range(0,len(distributions)):
    #kmeans = sklearn.cluster.k_means(distributions[j][1],n_clusters=4, random_state=52365,sample_weight=None)#.fit(distributions[j][1])
    LL = [1/distributions[j][1].shape[0] for i in np.arange(distributions[j][1].shape[0])]
            #print(LL)


    try:
        kmeans = KMeans(n_clusters=4, random_state=52365).fit(distributions[j][1],sample_weight=Repo)
        centroids = kmeans.cluster_centers_
        labels = fct.sorting_by_center_of_mass(kmeans.cluster_centers_,kmeans.labels_)
        distributions[j].append(1)
        label_color = [LABEL_COLOR_MAP[l] for l in labels]
        distributions[j].append(labels)
        distributions[j].append(silhouette_score(distributions[j][1], kmeans.labels_))
        distributions[j].append(centroids)
    except:
        distributions[j].append(0)
        continue

print(distributions[INDICE_TRUE][0])

Selector = {}
for r in range(0,len(distributions)):
    if distributions[r][2] == 0:
        pass
    else:
        Selector[r] = distributions[r][4]

INDICE_TRUE = list({k: v for k, v in sorted(Selector.items(), key=lambda item: item[1],reverse=True)}.keys())[0]

and im getting this error:


IndexError                                Traceback (most recent call last)
<ipython-input-480-d452250e06c1> in <module>
    227             Selector[r] = distributions[r][4]
    228 
--> 229     INDICE_TRUE = list({k: v for k, v in sorted(Selector.items(), key=lambda item: item[1],reverse=True)}.keys())[0]
    230 
    231     B_F_1['Label'] = distributions[INDICE_TRUE][3]

IndexError: list index out of range

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your for loop which assigns to to Selector is not guaranteed to make any assignments. If distributions[r][2] == 0 for every r, then Selector will be empty.

for r in range(0,len(distributions)):
    if distributions[r][2] == 0:
        pass
    else:
        Selector[r] = distributions[r][4]

By implication, this thing, whatever it is, cannot have the zero index at the end:

INDICE_TRUE = list({k: v for k, v in sorted(Selector.items(), key=lambda item: item[1],reverse=True)}.keys())[0]

My personal 2 cents: Pandas is hard, Numpy is hard, data structures are hard. If you're going to start out by mixing them all together in bad copy-pasted code you are going to struggle.

I say this code is bad because there is a lot of nasty stuff in here. For example, catching a bare exception is a recognised anti pattern, variable names don't follow PEP, there's magic numbers everywhere, and far too many compound statements to be able to make sense of what's going on. Start with a good tutorial on the standard libary, then learn numpy, then pandas, or you will struggle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...