在保留索引的同时对数据帧中的行进行洗牌

2024-05-14 18:48:18 发布

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

我目前正试图找到一种方法,在数据框中按行随机排列项目。我想保留列名和索引。我只想更改数据框中条目的顺序

目前,我正在使用

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

然而,这在产出方面造成了一些问题。我认为这些行没有被正确地洗牌。有没有其他方法可以做到这一点

问题是,我在做文本分析,当我在每个类中查看最相关的单图和双图时,我得到的是混合数据和原始数据的不同答案

这是我用于字母组合和双字母组合的代码

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:])))

Tags: 数据方法intrueformatfordatanames
1条回答
网友
1楼 · 发布于 2024-05-14 18:48:18

仅仅使用data = data.sample(frac=1)对索引进行采样也是有问题的。您可以看到下面的输出。我们只需要更改值

enter image description here

实现这一点的正确方法是仅对值进行采样。我刚想出来。我们可以这样做。谢谢所有试图帮忙的人

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

我从中得到了正确的输出

相关问题 更多 >

    热门问题