簡體   English   中英

改組 Pandas DataFrame 中的行,同時保留索引

[英]Shuffling rows in a Pandas DataFrame while retaining the index

我目前正在嘗試找到一種方法來按行隨機化 dataframe 中的項目。 我想保留列名以及索引。 我只想更改 dataframe 中的條目順序。

目前,我正在使用

data = data.sample(frac=1).reset_index(drop=True)

但是,這會導致 output 出現一些問題。 我不認為行被正確洗牌。 還有其他方法可以實現嗎?

問題是我正在做文本分析,當我查看每個 class 最相關的一元和二元時,我得到了洗牌和原始數據的不同答案。

這是我用於字母組合和雙字母組合的代碼

tfidf = TfidfVectorizer(sublinear_tf=True, 
                    min_df=5, 
                    stop_words=STOPWORDS, 
                    norm = 'l2', 
                    encoding='latin-1', 
                    ngram_range=(1, 2))

feat = tfidf.fit_transform(data['Combine']).toarray()

N = 5    # Number of examples to be listed
for f, i in sorted(category_labels.items()):
    chi2_feat = chi2(feat, labels == i)
    indices = np.argsort(chi2_feat[0])
    feat_names = np.array(tfidf.get_feature_names())[indices]
    unigrams = [w for w in feat_names if len(w.split(' ')) == 1]
    bigrams = [w for w in feat_names if len(w.split(' ')) == 2]
    print("\nFlair '{}':".format(f))
    print("Most correlated unigrams:\n\t. {}".format('\n\t. '.join(unigrams[-N:])))
    print("Most correlated bigrams:\n\t. {}".format('\n\t. '.join(bigrams[-N:])))

僅使用data = data.sample(frac=1)也會對索引進行采樣,這是有問題的。 您可以在下面看到 output。 我們只需要更改這些值。

在此處輸入圖像描述

實現此目的的正確方法是僅對值進行采樣。 我剛剛想通了。 我們可以這樣做。 感謝所有試圖提供幫助的人。

data[:] = data.sample(frac=1).values

我從中得到了正確的 output 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM