Python | Панды Series.sample ()

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

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.sample() function return a random sample of items from an axis of object. We can also use random_state for reproducibility.

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

Parameter :
n : Number of items from axis to return.
frac : Fraction of axis items to return.
replace : Sample with or without replacement.
weights : Default ‘None’ results in equal probability weighting.
random_state : Seed for the random number generator (if int), or numpy RandomState object.
axis : Axis to sample.

Returns : Series or DataFrame

Example #1: Use Series.sample() function to draw random sample of the values from the given Series object.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio", "Moscow"])
  
# Create the Datetime Index
index_ = ["City 1", "City 2", "City 3", "City 4", "City 5", "City 6"]
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Output :

Now we will use Series.sample() function to draw a random sample of values from the given Series object.

# Draw random sample of 3 values
selected_cities = sr.sample(n = 3)
  
# Print the returned Series object
print(selected_cities)

Output :

As we can see in the output, the Series.sample() function has successfully returned a random sample of 3 values from the given Series object.
 
Example #2: Use Series.sample() function to draw random sample of the values from the given Series object.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([100, 25, 32, 118, 24, 65])
  
# Create the Index
index_ = ["Coca Cola", "Sprite", "Coke", "Fanta", "Dew", "ThumbsUp"]
  
# set the index
sr.index = index_
  
# Print the series
print(sr)

Выход :

Now we will use Series.sample() function to select a random sample of size equivalent to 25% of the size of the given Series object.

# Draw random sample of size of 25 % of the original object
selected_items = sr.sample(frac = 0.25)
  
# Print the returned Series object
print(selected_items)

Выход :

As we can see in the output, the Series.sample() function has successfully returned a random sample of 2 values from the given Series object, which is 25% of the size of the original series object.

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

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