Write a Python program to shuffle all the elements in a given series

PythonPandasServer Side ProgrammingProgramming

Assume, you have a dataframe and the result for shuffling all the data in a series,

The original series is
0    1
1    2
2    3
3    4
4    5
dtype: int64
The shuffled series is :
0    2
1    1
2    3
3    5
4    4
dtype: int64

Solution 1

  • Define a series.

  • Apply random shuffle method takes series data as an argument and shuffles it.

data = pd.Series([1,2,3,4,5])
print(data)
rand.shuffle(data)

Example

Let’s see the below code to get a better understanding −

import pandas as pd
import random as rand
data = pd.Series([1,2,3,4,5])
print("original series is\n",data)
rand.shuffle(data)
print("shuffles series is\n",data)

Output

original series is
0    1
1    2
2    3
3    4
4    5
dtype: int64
shuffles series is
0    2
1    3
2    1
3    5
4    4
dtype: int64

Solution 2

  • Define a series.

  • Create for loop to access series data and generate random index in j variable. It is defined below,

for i in range(len(data)-1, 0, -1):
   j = random.randint(0, i + 1)
  • Swap data[i] with the element at random index position,

data[i], data[j] = data[j], data[i]

Example

Let’s see the below code to get a better understanding −

import pandas as pd
import random
data = pd.Series([1,2,3,4,5])
print ("The original series is \n", data)
for i in range(len(data)-1, 0, -1):
   j = random.randint(0, i + 1)
   data[i], data[j] = data[j], data[i]
print ("The shuffled series is : \n ", data)

Output

The original series is
0    1
1    2
2    3
3    4
4    5
dtype: int64
The shuffled series is :
0    2
1    1
2    3
3    5
4    4
dtype: int64
raja
Published on 11-Feb-2021 14:59:59
Advertisements