【问题标题】:Python: Is there a way to randomly split data from pandas dataframe into train and validation setPython:有没有办法将数据从熊猫数据框中随机拆分为训练集和验证集
【发布时间】:2021-04-07 11:55:59
【问题描述】:

我有一个稀疏矩阵,每列包含未来的价格。我希望将数据随机分成两组。 我知道 sklearn 中的 train_test_split 可以将数据随机分成两组,但是它不能满足我的需求:

  1. 随机选择的数据应排除 nans
  2. 从每列中提取不同大小的数据。(例如,第一列包含 10000 个非 nan 单元格,第二列包含 5000 个,我需要从第一列中提取 2000 个单元格,从第二列中提取 500 个作为训练集,其余作为验证集)

有没有节省时间的方法?

【问题讨论】:

  • 您可能应该只使用 pd.Series.sample() 对不同列进行不同的采样值,然后将结果列连接到数据帧中。
  • sparse matrix 与 pandas 数据框有什么关系?认真考虑将您的数据转换为sklearn 可以轻松拆分的形式。如果它不能拆分它,它可能也无法从中学习。
  • 感谢您的回复。但是我觉得pd.Series.sample()还是不能排除nans,用什么样的数据形式都无所谓,我只需要实现上面提到的目标,不用太多循环

标签: python pandas numpy machine-learning


【解决方案1】:

您可以尝试以下方法:

# Randomize the dataset
data_randomized = sms_spam.sample(frac=1, random_state=1)

# Calculate index for split 80:20 ratio
training_test_index = round(len(data_randomized) * 0.8)

# Split into training and test sets
training_set = data_randomized[:training_test_index].reset_index(drop=True)
test_set = data_randomized[training_test_index:].reset_index(drop=True)

print(training_set.shape)
print(test_set.shape)

来源:link

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 2016-09-13
    • 1970-01-01
    • 2019-04-22
    • 2020-10-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 2021-05-08
    相关资源
    最近更新 更多