为了账号安全,请及时绑定邮箱和手机立即绑定

For循环数据框:如何打印索引名称而不是数字 i 和 j?

For循环数据框:如何打印索引名称而不是数字 i 和 j?

烙印99 2024-01-04 16:23:02
我有一个数据框:行索引都是人名。列索引是对 7 个不同问题的所有评分 1-10。因此,数据框由 1-10 的所有数字组成:每个人(行)的每个问题(列)的数字。它看起来像这样:        Q1.    Q2.    Q3.   Q4.   Q5.   Q6.   Q7.     Lotte   4      6      4     5     8     6      5Lara    5      7      8     7     9     7      6Linda   7      7      8     8     7     8      6Tom     9      8      7     9     6     9      7Jantje  9      9      9     10    7     10     8然后我想创建一个 for 循环来遍历这些数据(称为“分数”),检查每个数字。如果数字<5,我想打印:“对于“QUESTION”的“NAME”,它低于5”。所以,fe:对于乐天来说,第一季度它低于 5。我现在有以下代码:for i in range(len(Score.columns)):    for j in range(len(Score)):        if Score.iloc[j,i] < 5:            print ("Lower for %d" %i)这仅打印列号,但我想打印列和行,但由索引命名。谁能帮忙打印这个吗?
查看完整描述

1 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

这是相当简单的


您可以使用数据框方法iterrows来迭代您的行,然后处理单行以提取您的知识。为了完整起见,我生成了一个示例数据框来演示该行为:


import pandas as pd

import random

# here I am generating my dataframe similiar to yours

list_of_dicts = [{'Q'+str(i)+'.':random.randrange(10) for i in range(1, 8)} for j in range(5)]

index = ['Lotte', 'Lara', 'Linda', 'Tom', 'jantje']


df = pd.DataFrame(list_of_dicts)

df.index = index


# here you can see the df structure 

print(df)


# here the algorithm

for row in df.iterrows():

  name = row[0]

  print("For " + name)

  for key in row[1].keys():

    if row[1][key] < 5:

      print("for {} it is Lower than 5".format(key))

我的数据框:


        Q1.  Q2.  Q3.  Q4.  Q5.  Q6.  Q7.

Lotte     6    8    5    8    8    1    6

Lara      1    7    0    7    5    5    1

Linda     6    6    0    3    9    7    4

Tom       5    8    2    5    3    8    3

jantje    5    5    9    9    5    0    3

我的输出:


For Lotte

for Q6. it is Lower than 5

For Lara

for Q1. it is Lower than 5

for Q3. it is Lower than 5

for Q7. it is Lower than 5

For Linda

for Q3. it is Lower than 5

for Q4. it is Lower than 5

for Q7. it is Lower than 5

For Tom

for Q3. it is Lower than 5

for Q5. it is Lower than 5

for Q7. it is Lower than 5

For jantje

for Q6. it is Lower than 5

for Q7. it is Lower than 5


查看完整回答
反对 回复 2024-01-04
  • 1 回答
  • 0 关注
  • 44 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信