【问题标题】:How to print each row of a Dataframe including the column names?如何打印包含列名的数据框的每一行?
【发布时间】:2021-04-27 05:45:34
【问题描述】:

我的数据框设置如下:

Project CriteriaOne CriteriaTwo CriteriaThree
Proj A  Comments A  Comments B  Comments C   
Proj B  Comments D  Comments E  Comments F   
Proj C  Comments G  Comments H  Comments I   

我想写入以下格式的文件:

Proj A
Criteria One: Comments A
Criteria Two: Comments B
Criteria Three: Comments C

Proj B
Criteria One: Comments D
Criteria Two: Comments E
Criteria Three: Comments F

Proj C
Criteria One: Comments G
Criteria Two: Comments H
Criteria Three: Comments I

我已经使用 enumerate(是的,我知道它不正确)、iterrows(是的,我知道它很慢)和 itertuples 玩过一堆代码 sn-ps,虽然我可以通过每一个,我都觉得我忽略了一些明显的东西。

理想情况下,我不会按名称引用“CriteriaOne”,因为我正在转换几个使用相同格式的不同内容,但“CriteriaOne”将在另一个文件中命名为“FlarbleOne”。

我已经完成了其他部分(使用 groupby 合并多行,以及必要的文件处理),但我还没有完全理解这一重要部分。迭代这个数据框并在输出中做一些漂亮的标签的优雅方法是什么?

【问题讨论】:

    标签: python pandas printing iteration


    【解决方案1】:

    我们可以通过迭代每一行来做到这一点。我假设你想把它写在 txt 文件中

    数据框创建:

    import pandas as pd
    col = ["Project", "CriteriaOne", "CriteriaTwo", "CriteriaThree"]
    data = [["Proj A",  "Comments A",  "Comments B",  "Comments C"],   
    ["Proj B",  "Comments D",  "Comments E",  "Comments F"],
    ["Proj C",  "Comments G",  "Comments H",  "Comments I" ]]
    
    df = pd.DataFrame(data, columns=col)
    

    数据框:

    Project CriteriaOne CriteriaTwo CriteriaThree
    0   Proj A  Comments A  Comments B  Comments C
    1   Proj B  Comments D  Comments E  Comments F
    2   Proj C  Comments G  Comments H  Comments I
    

    代码

    with open("./temp.txt", "w") as file:
        for _, row in df.iterrows():
            file.write(row[0]+"\n")
            for key, value in row[1:].items():
                file.write(key+": "+value+"\n")
            file.write("\n")
        
    

    输出:

    Proj A
    CriteriaOne: Comments A
    CriteriaTwo: Comments B
    CriteriaThree: Comments C
    
    Proj B
    CriteriaOne: Comments D
    CriteriaTwo: Comments E
    CriteriaThree: Comments F
    
    Proj C
    CriteriaOne: Comments G
    CriteriaTwo: Comments H
    CriteriaThree: Comments I
    

    【讨论】:

    • 这很好——我在解决类型以使其工作并解决我所做的其他一些修改时遇到了一些问题,但这使得调整最终格式变得容易,并且在我阅读时很有意义(尤其是作为曾经涉足 perl 的人)。谢谢!
    【解决方案2】:

    假设你的数据框是

    f = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},'B': {0: 1, 1: 3, 2: 5},'C': {0: 2, 1: 4, 2: 6}})
    

    输出:

       A  B  C
    0  a  1  2
    1  b  3  4
    2  c  5  6
    

    只是迭代

    for i in f.index:
     print()
     print(i)
     for j in f.columns:
       print(f'{j} : {f.iloc[i][j]}')
    

    将输出为

    0
    A : a 
    B : 1 
    C : 2 
    
    1
    A : b 
    B : 3 
    C : 4 
    
    2
    A : c 
    B : 5 
    C : 6 
    

    【讨论】:

      【解决方案3】:

      想法是将Project 列转换为index 并通过DataFrame.to_dict 创建的字典循环,将值添加到Series 并附加到带有标题的文件:

      df = df.set_index('Project')
      
      with open('file.csv', 'a') as file:
          for i, j in df.T.to_dict(orient='series').items():
              s = j.index + ': ' + j
              
              file.write(f'{i}\n')
              s.to_csv(file, header=False, index=False, line_terminator='\n')
              file.write('\n')
      

      【讨论】:

      • 我喜欢这里的哲学方法。现在我已经让它在上面工作了,我想回去玩这个,因为它感觉就像更简单的模型。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2019-07-01
      • 2013-03-30
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多