【问题标题】:Convert dataframe to dictionary but not to take column name as keys in python将数据框转换为字典但不将列名作为python中的键
【发布时间】:2018-11-02 13:35:26
【问题描述】:

我在下面给出了一个 daframe。我想把它转换成字典。但我不希望列名作为键。

data = {'0':[0.039169993,0.023344912], '1':[0.17865846,0.01093025],'2':[0.039170124,0.023344917], '3':[0.17865846,0.01093025],'4':[0.039170124,0.023344917]}
df= pd.DataFrame(data)



         0.0            1.0          2.0        3.0          4.0
0  0.039169993   0.17865846  0.039170124   0.17865846  0.039170124
1  0.023344912   0.01093025  0.023344917   0.01093025  0.023344917

**Desired Result**:
    {{0: 0.039169993, 1:0.023344912},
     {0: 0.17865846, 1:0.01093025},
     {0: 0.039170124, 1:0.023344917},
     {0: 0.17865846, 1:0.01093025},
     {0:0.039170124, 1:0.023344917}}

我的尝试:

df.to_dict()
{'0': {0: 0.039169993, 1: 0.023344912},
 '1': {0: 0.17865846, 1: 0.01093025},
 '2': {0: 0.039170124, 1: 0.023344917},
 '3': {0: 0.17865846, 1: 0.01093025},
 '4': {0: 0.039170124, 1: 0.023344917}}

我不希望列名作为键。有可能吗?

【问题讨论】:

    标签: python dictionary dataframe


    【解决方案1】:

    您可以使用transposeT.to_dict(orient='records') 来获得所需的输出,例如:

    df.T.to_dict(orient='records')
    

    【讨论】:

      【解决方案2】:

      所需结果具有一组字典的格式,但您不能拥有一组字典,因为字典不可散列,但您可以拥有一个列表。

      import pandas as pd
      
      data = {'0': [0.039169993, 0.023344912], '1': [0.17865846, 0.01093025], '2': [0.039170124, 0.023344917],
              '3': [0.17865846, 0.01093025], '4': [0.039170124, 0.023344917]}
      df = pd.DataFrame(data)
      
      result = list(df.to_dict().values())
      
      print(result)
      

      输出

      [{0: 0.039170124, 1: 0.023344917}, {0: 0.039169993, 1: 0.023344912}, {0: 0.17865846, 1: 0.01093025}, {0: 0.17865846, 1: 0.01093025}, {0: 0.039170124, 1: 0.023344917}]
      

      【讨论】:

        【解决方案3】:

        你可以用这个:

        df.T.to_dict(orient='records')
        
        [{0: 0.039169993, 1: 0.023344911999999999},
         {0: 0.17865845999999999, 1: 0.010930250000000001},
         {0: 0.039170124000000001, 1: 0.023344917},
         {0: 0.17865845999999999, 1: 0.010930250000000001},
         {0: 0.039170124000000001, 1: 0.023344917}]
        

        【讨论】:

          猜你喜欢
          • 2021-08-24
          • 1970-01-01
          • 2016-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-31
          • 1970-01-01
          相关资源
          最近更新 更多