使用 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 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.