我想把数据帧分成有范围的列车和测试集

2024-04-26 05:19:34 发布

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

import pandas as pd 
import numpy as np
data=[]
columns = ['A', 'B', 'C']
data = [[0, 10, 5], [0, 12, 5], [2, 34, 13], [2, 3, 13], [4, 5, 8], [2, 4, 8], [1, 2, 4], [1, 3, 4], [3, 8, 12],[4,10,12],[6,7,12]]

df = pd.DataFrame(data, columns=columns)
print(df)

#     A   B   C
# 0   0  10   5
# 1   0  12   5
# 2   2  34  13
# 3   2   3  13
# 4   4   5   8
# 5   2   4   8
# 6   1   2   4
# 7   1   3   4
# 8   3   8  12
# 9   4  10  12
# 10  6   7  12

现在我想创建两个数据帧df_train和df_test,这样就不会有两个列“C”在同一个集合中。例如,在C列中,元素5应该在训练集或测试集中,因此,行[0,10,5],[0,12,5],[2,34,13]将要么放入训练集,要么放入测试集,但不在训练集中都是。这个C列元素的选择应随机进行。在

我被困在这一步,无法继续。在


Tags: columns数据testimportnumpy元素dataframepandas
2条回答

首先sample您的df,然后groupbyC得到cumcount在同一组中的重复值。在

s=df.sample(len(df)).groupby('C').cumcount()
s
Out[481]: 
5     0
7     0
2     0
1     0
0     1
6     1
10    0
4     1
3     1
8     1
9     2
dtype: int64
test=df.loc[s[s==1].index]
train=df.loc[s[s==0].index]
test
Out[483]: 
   A   B   C
0  0  10   5
6  1   2   4
4  4   5   8
3  2   3  13
8  3   8  12
train
Out[484]: 
    A   B   C
5   2   4   8
7   1   3   4
2   2  34  13
1   0  12   5
10  6   7  12

问题不太清楚两个列车和测试集数据帧的预期输出应该是什么样子。在

不管怎样,我会尽力回答的。在

我认为您可以先对数据帧值进行排序:

df_sorted = df.sort_values(['C'], ascending=[True])
print(df_sorted)

Out[1]:
    A   B   C
6   1   2   4
7   1   3   4
0   0  10   5
1   0  12   5
4   4   5   8
5   2   4   8
8   3   8  12
9   4  10  12
10  6   7  12
2   2  34  13
3   2   3  13

然后拆分已排序的数据帧:

^{pr2}$

从11个样本中,分离后,6个样本进入序列集,5个样本进入验证集。所以,检查和没有丢失的样本在总的两个数据帧组合。在

相关问题 更多 >