Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโค้ด Python สุ่มเลือก 1 แถวจาก DataFrame

สมมติว่าคุณมี DataFrame และต้องการสุ่มเลือก 1 แถว

วิธีแก้ปัญหา

  1. สร้าง DataFrame
  2. หาจำนวนแถวด้วย df.shape[0]
  3. สุ่มเลข index ด้วย random.randrange(rows)
  4. ดึงแถวด้วย df.iloc[random_row, :]

ตัวอย่างโค้ด

import pandas as pd
import random as r

data = {'Id': [1, 2, 3, 4, 5], 'Name': ['Adam', 'Michael', 'David', 'Jack', 'Peter']}
df = pd.DataFrame(data)

print("DataFrame:\n", df)

rows = df.shape[0]
print("จำนวนแถวทั้งหมด:", rows)

random_row = r.randrange(rows)
print("Index ที่สุ่มได้:", random_row)

print("\nแถวที่สุ่มได้:")
print(df.iloc[random_row, :])

ผลลัพธ์ตัวอย่าง

DataFrame:
   Id     Name
0   1     Adam
1   2  Michael
2   3    David
3   4     Jack
4   5    Peter

จำนวนแถวทั้งหมด: 5
Index ที่สุ่มได้: 3

แถวที่สุ่มได้:
Id     4
Name   Jack
Name: 3, dtype: object

คำอธิบาย:

  • df.shape[0] คืนจำนวนแถว
  • random.randrange(n) สุ่มจำนวนเต็ม 0 ถึง n-1
  • df.iloc[row, :] ดึงแถวทั้งหมดของ index นั้น
  • วิธีที่ง่ายกว่า: ใช้ df.sample(n=1) หรือ df.sample(frac=1).iloc[0] ซึ่งเป็น pandas native method