編寫 Python 程式碼,從給定的 DataFrame 中選擇任一行


輸入

假定,示例 DataFrame 是,

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

輸出

Random row is
  Id    5
Name Peter

解決方案

為了解決這個問題,我們將遵循以下方法。

  • 定義一個 DataFrame

  • 使用 df.shape[0] 計算行數,並將其分配給行變數。

  • 如下所示,從 randrange 方法中設定 random_row 值。

random_row = r.randrange(rows)
  • 在 iloc 切片中應用 random_row 以生成 DataFrame 中的任意一行。如下定義,

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 is\n", df)
rows = df.shape[0]
print("total number of rows:-", rows)
random_row = r.randrange(rows)
print("print any random row is\n")
print(df.iloc[random_row,:])

輸出

DataFrame is
 Id Name
0 1 Adam
1 2 Michael
2 3 David
3 4 Jack
4 5 Peter
total number of rows:- 5
print any random row is
  Id   3
Name David

更新日期: 2021 年 2 月 24 日

383 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.