【问题标题】:Shuffling rows in a Pandas DataFrame while retaining the index在保留索引的同时对 Pandas DataFrame 中的行进行改组
【发布时间】:2020-09-12 04:51:52
【问题描述】:

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

目前,我正在使用

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

【问题讨论】:

  • 输出有什么问题?是什么让你认为行没有被洗牌?你的代码在我看来是正确的。
  • 你想reset_index 吗?如果你想保留索引,那么 data = data.sample(frac=1) 就足够了
  • 嗨,我刚刚做了那个编辑。我希望这能让它更清楚。
  • @NYCCoder 仅使用 data = data.sample(frac=1) 不起作用,因为它也会对索引进行采样。

标签: python pandas dataframe shuffle


【解决方案1】:

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

实现此目的的正确方法是对值进行采样。我刚刚想通了。我们可以这样做。感谢所有试图提供帮助的人。

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

我从中得到了正确的输出。

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 2020-02-17
    • 2023-03-20
    • 2023-02-01
    • 2013-09-08
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多