สมมติว่าคุณมี dataframe
DataFrame is: 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
และผลลัพธ์สำหรับการเลือกแถวดัชนีคี่แบบสุ่มคือ
Random odd index row is: id 4 mark 50 age 13
วิธีแก้ปัญหา
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนด้านล่าง -
-
กำหนดดาต้าเฟรม
-
สร้างรายการว่างเพื่อผนวกค่าดัชนีคี่
-
สร้าง for loop เพื่อเข้าถึงดัชนีทั้งหมด มีการกำหนดไว้ด้านล่าง
for i in df.index.values:
-
สร้างเงื่อนไข if เพื่อตรวจสอบดัชนีคี่ หากตรงกัน ให้เพิ่มค่าลงในรายการ
if(i%2==1): l.append(i)
-
สร้างค่าสุ่มใดๆ จากรายการและจัดเก็บค่า random_index
random_index = rand.choice(l)
-
สุดท้าย ให้พิมพ์แถวดัชนีคี่โดยใช้ iloc
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 is:\n",df)
l = []
for i in df.index.values:
if(i%2==1):
l.append(i)
random_index = rand.choice(l)
print("Random odd index row is: \n", df.iloc[random_index]) ผลลัพธ์
DataFrame is: 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 Random odd index row is: id 4 mark 50 age 13 Name: 3, dtype: int64