使用 Python 編寫程式,從給定的 DataFrame 中選擇任意隨機的奇數索引行。


假設你有一個 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

解決方案

為了解決這個問題,我們將按照以下步驟操作:

  • 定義一個 DataFrame

  • 建立一個空列表,用於追加奇數索引的值

  • 建立一個 for 迴圈來訪問所有索引,定義如下:

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

更新於: 2021年2月24日

621 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告