【问题标题】:Get header:row_data from CSV file python从 CSV 文件 python 获取 header:row_data
【发布时间】:2015-02-07 22:36:39
【问题描述】:

我有一个如下所示的 csv 文件

h1,h2,h3,h4
a,b,,d
1,2,3,4
a1,,h5,jj

我想要一个这样的列表: 例如,对于“a”,我需要h1:a,h2:b,h4:d。我可以分别获取标题和行数据,但是,我无法以所需的方式连接它们。另外,我不希望将空白打印为“nan”

【问题讨论】:

  • 你的意思是字典列表?
  • @reptilecus 是的。但它应该只打印 h1 的一个元素,即 a 或 1 或 a1。我为完整的字典尝试了{rows[0]:rows[1] for rows in reader},但输出看起来很糟糕。
  • df.to_dict('records') 可能有用吗?
  • 它为空白单元格提供“nan”。我希望它们被完全忽略。 @reptilicus

标签: python csv numpy dictionary pandas


【解决方案1】:

这样的事情可能会奏效

import numpy as np
import pandas
df = pandas.read_csv('some_file')
for row in df.to_dict('records'):
   print {k:v for k,v in row.iteritems() if v is not np.nan}

【讨论】:

    【解决方案2】:

    您可以使用 csv 模块和 dict 理解轻松做到这一点:

    import csv
    
    with open('test.csv', 'r') as f:                                                                                                                                  
            reader = csv.reader(f)                                                                                                                                        
            result = []                                                                                                                                                   
            header = reader.next()                                                                                                                                        
            for row in reader:                                                                                                                                            
                result.append({k: v for k, v in zip(header, row) if v != ''}) 
    

    【讨论】:

      【解决方案3】:

      您也可以使用我的包装库而不是 csv 模块来做到这一点:

      >>> import pyexcel as pe
      >>> s=pe.load("example.csv", name_columns_by_row=0)
      >>> records = s.to_records()
      >>> records
      [{'h2': u'b', 'h3': u'', 'h1': u'a', 'h4': u'd'}, {'h2': u'2', 'h3': u'3', 'h1': u'1', 'h4': u'4'}, {'h2': u'', 'h3': u'h5', 'h1': u'a1', 'h4': u'jj'}]
      >>> s.column['h1']
      [u'a', u'1', u'a1']
      >>> zip(s.column['h1'], records)
      [(u'a', {'h2': u'b', 'h3': u'', 'h1': u'a', 'h4': u'd'}), (u'1', {'h2': u'2', 'h3': u'3', 'h1': u'1', 'h4': u'4'}), (u'a1', {'h2': u'', 'h3': u'h5', 'h1': u'a1', 'h4': u'jj'})]
      

      更多文档可以找到here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-17
        • 2019-05-23
        • 2013-01-21
        • 1970-01-01
        • 2019-04-18
        相关资源
        最近更新 更多