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

我有一个数据框:

  • 行索引都是人名。

  • 列索引是对 7 个不同问题的所有评分 1-10。

因此,数据框由 1-10 的所有数字组成:每个人(行)的每个问题(列)的数字。它看起来像这样:

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

Lotte   4      6      4     5     8     6      5

Lara    5      7      8     7     9     7      6

Linda   7      7      8     8     7     8      6

Tom     9      8      7     9     6     9      7

Jantje  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)

这仅打印列号,但我想打印列和行,但由索引命名。谁能帮忙打印这个吗?


烙印99
浏览 90回答 1
1回答

RISEBY

这是相当简单的您可以使用数据框方法iterrows来迭代您的行,然后处理单行以提取您的知识。为了完整起见,我生成了一个示例数据框来演示该行为:import pandas as pdimport random# here I am generating my dataframe similiar to yourslist_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&nbsp;print(df)# here the algorithmfor row in df.iterrows():&nbsp; name = row[0]&nbsp; print("For " + name)&nbsp; for key in row[1].keys():&nbsp; &nbsp; if row[1][key] < 5:&nbsp; &nbsp; &nbsp; print("for {} it is Lower than 5".format(key))我的数据框:&nbsp; &nbsp; &nbsp; &nbsp; Q1.&nbsp; Q2.&nbsp; Q3.&nbsp; Q4.&nbsp; Q5.&nbsp; Q6.&nbsp; Q7.Lotte&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 8&nbsp; &nbsp; 5&nbsp; &nbsp; 8&nbsp; &nbsp; 8&nbsp; &nbsp; 1&nbsp; &nbsp; 6Lara&nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; 7&nbsp; &nbsp; 0&nbsp; &nbsp; 7&nbsp; &nbsp; 5&nbsp; &nbsp; 5&nbsp; &nbsp; 1Linda&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; 6&nbsp; &nbsp; 0&nbsp; &nbsp; 3&nbsp; &nbsp; 9&nbsp; &nbsp; 7&nbsp; &nbsp; 4Tom&nbsp; &nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; 8&nbsp; &nbsp; 2&nbsp; &nbsp; 5&nbsp; &nbsp; 3&nbsp; &nbsp; 8&nbsp; &nbsp; 3jantje&nbsp; &nbsp; 5&nbsp; &nbsp; 5&nbsp; &nbsp; 9&nbsp; &nbsp; 9&nbsp; &nbsp; 5&nbsp; &nbsp; 0&nbsp; &nbsp; 3我的输出:For Lottefor Q6. it is Lower than 5For Larafor Q1. it is Lower than 5for Q3. it is Lower than 5for Q7. it is Lower than 5For Lindafor Q3. it is Lower than 5for Q4. it is Lower than 5for Q7. it is Lower than 5For Tomfor Q3. it is Lower than 5for Q5. it is Lower than 5for Q7. it is Lower than 5For jantjefor Q6. it is Lower than 5for Q7. it is Lower than 5
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python