【问题标题】:Python .csv into dictionaryPython .csv 到字典
【发布时间】:2018-09-24 16:49:17
【问题描述】:

我要转换以下csv

E1;4;6;7;1;3;6
E2;5;4;3;5;0;0
E3;2;3;3;0;0;0

放入具有以下结构的 Python 字典:

d = {"E1": np.array([4,6,7,1,3,6])}
d["E2"] = np.array([5,4,3,5,0,0])

有没有简单的方法来做到这一点?非常感谢。

【问题讨论】:

  • 请根据您对该任务的研究,展示您尝试过的内容
  • 这个文件有多大?
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 On topichow to ask... the perfect question 在此处申请。 StackOverflow 不是设计、编码、研究或教程资源。但是,如果您遵循您在网上找到的任何资源,进行诚实的编码尝试并遇到问题,那么您将有一个很好的示例可以发布。
  • 文件大约有50行10列

标签: python dictionary


【解决方案1】:

使用pandas

>>> d = pd.read_csv('file.csv', sep=';', header=None).set_index(0).agg(np.array,1).to_dict()

{'E1': array([4, 6, 7, 1, 3, 6]),
 'E2': array([5, 4, 3, 5, 0, 0]),
 'E3': array([2, 3, 3, 0, 0, 0])}

使用纯python:

with open('file.csv', 'r') as f:
    d = {}
    for line in f:
        l = line.strip().split(';')
        d[l[0]] = np.array(list(map(int, l[1:])))

{'E1': array([4, 6, 7, 1, 3, 6]),
 'E2': array([5, 4, 3, 5, 0, 0]),
 'E3': array([2, 3, 3, 0, 0, 0])}

【讨论】:

    【解决方案2】:

    您可以读入 Pandas 数据框,转置然后使用字典理解:

    from io import StringIO
    
    x = StringIO("""E1;4;6;7;1;3;6
    E2;5;4;3;5;0;0
    E3;2;3;3;0;0;0""")
    
    # replace x with 'file.csv'
    df = pd.read_csv(x, sep=';', header=None).set_index(0).T
    
    d = {col: df[col].values for col in df}
    

    结果:

    {'E1': array([4, 6, 7, 1, 3, 6], dtype=int64),
     'E2': array([5, 4, 3, 5, 0, 0], dtype=int64),
     'E3': array([2, 3, 3, 0, 0, 0], dtype=int64)}
    

    如果list 值足够,可以使用to_dict

    d = pd.read_csv(x, sep=';', header=None).set_index(0).T.to_dict('list')
    

    【讨论】:

      【解决方案3】:
      df = pd.read_csv('input_file')
      column_names = df.columns.tolist()
      dict = {}
      for col in column_names:
          dict[column_names[col]] = column_names.col.values
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 2015-08-21
        相关资源
        最近更新 更多