Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thay thế vị trí index lẻ bằng nguyên âm in hoa ngẫu nhiên Python

Mô tả bài toán

Cho Series: [1, 2, 3, 4, 5].

Yêu cầu: Thay thế các phần tử tại index lẻ (1, 3, ...) bằng nguyên âm in hoa ngẫu nhiên (A, E, I, O, U).

Giải pháp

Duyệt qua Series, nếu index lẻ thì gán giá trị mới là nguyên âm ngẫu nhiên.

Ví dụ code hoàn chỉnh

import pandas as pd
import random as r

l = [1, 2, 3, 4, 5]
data = pd.Series(l)
print("Series gốc:")
print(data)

vowels = list("AEIOU")

for idx, val in data.items():
    if idx % 2 != 0:  # index lẻ
        data[idx] = r.choice(vowels)

print("\nSeries sau khi thay thế index lẻ:")
print(data)

Đầu ra mẫu

Series gốc:
0    1
1    2
2    3
3    4
4    5
dtype: int64

Series sau khi thay thế index lẻ:
0    1
1    O
2    3
3    E
4    5
dtype: object

Cải tiến: Vector hóa với numpy.where

import pandas as pd
import numpy as np
import random

data = pd.Series([1, 2, 3, 4, 5])
vowels = np.array(list("AEIOU"))

# Tạo mảng nguyên âm ngẫu nhiên cho tất cả index lẻ
odd_indices = data.index % 2 != 0
random_vowels = np.random.choice(vowels, size=odd_indices.sum())

# Gán vector hóa
data.loc[odd_indices] = random_vowels
print(data)

Lưu ý quan trọng

  • Sau khi gán chuỗi vào Series số, dtype chuyển từ int64 sang object.
  • Code gốc dùng data[i] = "".join(r.choice(vowels)) - join thừa vì choice đã trả về string đơn.
  • Cách vector hóa nhanh hơn và tránh warning SettingWithCopyWarning.