Разделите фрейм данных Pandas случайным образом в заданном соотношении

Опубликовано: 27 Марта, 2022

Задача Divide a Pandas Dataframe очень полезна в случае разделения данного набора данных на обучающие и тестовые данные для целей обучения и тестирования в области машинного обучения, искусственного интеллекта и т. Д. Давайте посмотрим, как разделить фрейм данных pandas случайным образом на заданные соотношения. Для этой задачи мы будем использовать Dataframe.sample () и Dataframe.drop () методы pandas dataframe вместе.

Синтаксис этих функций следующий:

  • Dataframe.sample ()

Syntax: DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None)

Return Type: A new object of same type as caller containing n items randomly sampled from the caller object.

  • Dataframe.drop ()

Syntax: DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)

Return: Dataframe with dropped values.

Example: Now, let’s create a Dataframe:

Python3

# Importing required libraries
import pandas as pd
  
record =
    "course_name": ["Data Structures", "Python",
                    "Machine Learning", "Web Development"],
    "student_name": ["Ankit", "Shivangi"
                     "Priya", "Shaurya"],
    "student_city": ["Chennai", "Pune"
                     "Delhi", "Mumbai"],
    "student_gender": ["M", "F",
                       "F", "M"] }
  
# Creating a dataframe
df = pd.DataFrame(record)
  
# show the dataframe
df

Выход:

Dataframe

Example 1: Divide a Dataframe randomly into a 1:1 ratio.

Python3

# Importing required libraries
import pandas as pd
  
record =
    "course_name": ["Data Structures", "Python",
                    "Machine Learning", "Web Development"],
    "student_name": ["Ankit", "Shivangi"
                     "Priya", "Shaurya"],
    "student_city": ["Chennai", "Pune"
                     "Delhi", "Mumbai"],
    "student_gender": ["M", "F",
                       "F", "M"] }
  
# Creating a dataframe
df = pd.DataFrame(record)
  
# Creating a dataframe with 50%
# values of original dataframe
part_50 = df.sample(frac = 0.5)
  
# Creating dataframe with 
# rest of the 50% values
rest_part_50 = df.drop(part_50.index)
  
print(" 50% of the givem DataFrame:")
print(part_50)
  
print(" rest 50% of the given DataFrame:")
print(rest_part_50)

Выход:

Разделить фрейм данных

Example 2: Divide a Dataframe randomly into a 3:1 ratio.

Python3

# Importing required libraries
import pandas as pd
  
record =
    "course_name": ["Data Structures", "Python",
                    "Machine Learning", "Web Development"],
    "student_name": ["Ankit", "Shivangi"
                     "Priya", "Shaurya"],
    "student_city": ["Chennai", "Pune"
                     "Delhi", "Mumbai"],
    "student_gender": ["M", "F",
                       "F", "M"] }
  
# Creating a dataframe
df = pd.DataFrame(record)
  
# Creating a dataframe with 75%
# values of original dataframe
part_75 = df.sample(frac = 0.75)
  
# Creating dataframe with 
# rest of the 25% values
rest_part_25 = df.drop(part_75.index)
  
print(" 75% of the givem DataFrame:")
print(part_75)
  
print(" rest 25% of the given DataFrame:")
print(rest_part_25)

Выход:

Разделить фрейм данных

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.