Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a program in Python to replace all odd index position in a given series by random uppercase vowels
In this tutorial, we'll learn how to replace values at odd index positions in a Pandas Series with random uppercase vowels. This is useful for data masking or creating test datasets.
Problem Statement
Given a Series with numeric values, we need to replace all values at odd index positions (1, 3, 5, etc.) with random uppercase vowels (A, E, I, O, U).
Input
0 1 1 2 2 3 3 4 4 5 dtype: int64
Expected Output
0 1 1 A 2 3 3 U 4 5 dtype: object
Solution
We'll use Pandas Series indexing and the random.choice() function to select random vowels for replacement ?
import pandas as pd
import random
# Create the original series
data_list = [1, 2, 3, 4, 5]
series = pd.Series(data_list)
print("Given series:")
print(series)
# Define uppercase vowels
vowels = list("AEIOU")
# Replace odd index positions with random vowels
for index, value in series.items():
if index % 2 != 0: # Check if index is odd
series[index] = random.choice(vowels)
print("\nModified series:")
print(series)
Given series: 0 1 1 2 2 3 3 4 4 5 dtype: int64 Modified series: 0 1 1 O 2 3 3 E 4 5 dtype: object
How It Works
Step 1: Create a Pandas Series with numeric values
Step 2: Define a list of uppercase vowels
Step 3: Iterate through the series using
items()to get both index and valueStep 4: Check if the index is odd using modulo operator (
%)Step 5: Replace odd-indexed values with randomly chosen vowels
Alternative Approach Using Vectorized Operations
For better performance with larger datasets, you can use vectorized operations ?
import pandas as pd
import random
# Create series
series = pd.Series([1, 2, 3, 4, 5, 6, 7, 8])
print("Original series:")
print(series)
# Get odd indices
odd_indices = series.index[series.index % 2 != 0]
# Generate random vowels for odd positions
vowels = ['A', 'E', 'I', 'O', 'U']
random_vowels = [random.choice(vowels) for _ in range(len(odd_indices))]
# Replace values at odd indices
series.loc[odd_indices] = random_vowels
print("\nModified series:")
print(series)
Original series: 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 dtype: int64 Modified series: 0 1 1 A 2 3 3 I 4 5 5 U 6 7 7 O dtype: object
Key Points
The Series dtype changes from
int64toobjectwhen strings are introducedIndex positions start from 0, so odd positions are 1, 3, 5, etc.
Each run produces different random vowels due to
random.choice()Use
items()to iterate through both index and values simultaneously
Conclusion
This approach effectively replaces odd-indexed values with random uppercase vowels using Pandas indexing and Python's random module. The vectorized approach is more efficient for larger datasets.
