用Python编写程序以选择给定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循环以访问所有索引。它的定义如下

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

猜你喜欢