如何使用Python获取带有dataframe列的选定行?

2024-04-28 22:15:45 发布

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

我的主要思想是将数据帧中具有多个列和行的数据分为训练数据集和测试数据集。在

编辑:我希望每次都使用相同的列车和测试数据。我尽量避免随机选择。

我试过了:

def splitTestandTrainData(datavalues):

    #create new dataframe with columns
    testDataFrame = pd.DataFrame(columns=datavalues.columns)

    #select every 4th row as a test data
    for i in range(1,len(datavalues.rows),4):

        #getting single row with all columns
        testDataFrame.append(datavalues.iloc(i))

        #and delete
        dataValues.drop(dataValues.index[i])

但我不能将行追加到新的数据帧中。我也不确定这是不是正确的方法。我怎么能做到呢?在

我的另一个问题是,如果我们想用选定的列来做呢?我的意思是我们如何能在空数据帧中追加行的列?在

提前谢谢


Tags: columns数据编辑newdefcreatewithrow
2条回答

您不需要手动执行此操作。
使用sklearn的train_test_split来完成它。在

from sklearn.model_selection import train_test_split
X, y = np.arange(10).reshape((5, 2)), range(5) # your input features and target value
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

如果你想用选定的列来做,那么在执行列车测试拆分之前,利用pandas的能力,只选择特定的列。在

^{pr2}$

使用pandas.DataFrame.sample()

测试数据帧=数据值.sample(分形=0.25)

将返回原始行的25%的随机样本。随机抽样还有许多其他选择。在

相关问题 更多 >