split data in python code example

Example 1: code for test and train split

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
 X, y, test_size=0.33, random_state=42)

Example 2: separate a string in python

string = "A B C D"
string2 = "E-F-G-H"

# the split() function will return a list
stringlist = string.split()
# if you give no arguments, it will separate by whitespaces by default
# ["A", "B", "C", "D"]

stringlist2 = string2.split("-", 3)
# you can specify the maximum amount of elements the split() function will output
# ["E", "F", "G"]

Example 3: split string python

file='/home/folder/subfolder/my_file.txt'
file_name=file.split('/')[-1].split('.')[0]

Example 4: splitting data into training and testing sklearn

train_features, test_features, train_labels, test_labels = 
train_test_split(features, labels)
#This is using sklearn

Tags:

Java Example