【问题标题】:Parsing CSV to python dictionary using pandas使用 pandas 将 CSV 解析为 python 字典
【发布时间】:2022-07-04 23:26:54
【问题描述】:

我已将以下 DataFrame 解析为 Python:

df = pd.read_csv("my_file.csv")

结果:

   indexes X_values Y_values
0       IDX1     x1      y1
1       IDX1     x2      y2
2       IDX1     x3      y3
3       IDX1     x4      y4
6       IDX2     x1      y1
9       IDX2     x4      y4
10      IDX3     x1      y1
11      IDX3     x2      y2

我需要创建字典,其中每个索引作为键,x_values 和 y_values 作为嵌套字典的列表。 输出应该是这样的:

{"IDX1" : [{"x1": "y1"}, {"x2": "y2"}, {"x3": "y3"}, {"x4": "y4"}],
"IDX2": [{"x1": "y1"},{"x4": "y4"}],
"IDX3":[{"x1": "y1"}, {"x2": "y2"}]}

我正在尝试使用 set_index() 方法解析它,但总是遗漏一些东西。你能帮帮我吗?

此外,以索引为键的嵌套字典的字典也是很好的解决方案。

【问题讨论】:

    标签: python pandas csv dictionary


    【解决方案1】:

    我们可以的

    d = df[['X_values','Y_values']].apply(lambda x : {x[0]:x[1]},axis=1).groupby(df['indexes']).agg(list).to_dict()
    Out[104]: 
    {'IDX1': [{'x1': 'y1'}, {'x2': 'y2'}, {'x3': 'y3'}, {'x4': 'y4'}],
     'IDX2': [{'x1': 'y1'}, {'x4': 'y4'}],
     'IDX3': [{'x1': 'y1'}, {'x2': 'y2'}]}
    

    【讨论】:

      【解决方案2】:

      听起来您需要使用to_dict() 方法(documentation)。

      您可能需要像您说的那样建立索引。我会尝试:

      df.set_index('indexes').T.to_dict('list')
      

      【讨论】:

        【解决方案3】:

        你可以试试

        out = (df.apply(lambda row: {row['X_values']: row['Y_values']}, axis=1)
               .groupby(df['indexes']).agg(list).to_dict())
        
        print(out)
        
        {'IDX1': [{'x1': 'y1'}, {'x2': 'y2'}, {'x3': 'y3'}, {'x4': 'y4'}], 'IDX2': [{'x1': 'y1'}, {'x4': 'y4'}], 'IDX3': [{'x1': 'y1'}, {'x2': 'y2'}]}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-05-01
          • 2016-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-04
          • 2017-11-05
          相关资源
          最近更新 更多