สมมติว่าคุณมี DataFrame และต้องการเลือกสุ่ม 1 แถวจากแถวที่มี index เป็นเลขคี่
วิธีแก้ปัญหา
- สร้าง DataFrame 2. สร้าง list เก็บ index ที่เป็นเลขคี่ 3. ใช้
random.choice() สุ่มเลือก 1 index จาก list
4. ใช้ df.iloc[random_index] ดึงแถวนั้นๆ
ตัวอย่างโค้ด
import pandas as pd
import random as rand
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6, 7],
'mark': [70, 60, 40, 50, 80, 90, 60],
'age': [12, 13, 12, 13, 12, 13, 12]})
print("DataFrame:\n", df)
# หา index ที่เป็นเลขคี่
odd_indices = [i for i in df.index if i % 2 == 1]
print("\nIndex คี่ที่พบ:", odd_indices)
# สุ่มเลือก 1 index
random_index = rand.choice(odd_indices)
print("Index ที่สุ่มได้:", random_index)
# แสดงแถวที่สุ่มได้
print("\nแถว index คี่แบบสุ่ม:")
print(df.iloc[random_index])
ผลลัพธ์ตัวอย่าง
DataFrame:
id mark age
0 1 70 12
1 2 60 13
2 3 40 12
3 4 50 13
4 5 80 12
5 6 90 13
6 7 60 12
Index คี่ที่พบ: [1, 3, 5]
Index ที่สุ่มได้: 3
แถว index คี่แบบสุ่ม:
id 4
mark 50
age 13
Name: 3, dtype: int64
คำอธิบาย:
- ใช้ list comprehension
[i for i in df.index if i % 2 == 1]หา index คี่ random.choice()สุ่มเลือก 1 element จาก listdf.iloc[random_index]ดึงแถวตาม integer position- ถ้า index ไใช่ 0,1,2... ต้องใช้
df.loc[random_index]แทน