【问题标题】:convert dataframe to dictionary excluding the ID将数据框转换为字典,不包括 ID
【发布时间】:2020-03-24 01:14:10
【问题描述】:

我的目标是创建一个嵌套字典,但我将随机数作为父键。这就是我到目前为止所做的:

result = result[['column1', 'column2','column3']]
result = result.to_dict('index')

all_result = {'ERR_CODE' : 0, 'ERR_MESSAGE' :'No error'}
all_result['LOC'] = result

我收到的结果:

{
  "ERR_CODE": 0,
  "ERR_MESSAGE": "No error",
  "LOC": {
    "792": {  #random number or possibly the row id
       "column1": "abc",
       "column2": "123",
       "column3": "def"
    }
  }
}

预期结果:

{
  "ERR_CODE": 0,
  "ERR_MESSAGE": "No error",
  "LOC": {
    "column1": "abc",
    "column2": "123",
    "column3": "def"
  }
}

在这种情况下我不能使用pop(792),因为这个数字是随机的。有什么方法可以使用pop 使用索引吗?或任何其他替代品..

更新 给出的答案解决了上述问题,但是如果结果下面有多个孩子怎么办,例如(预期结果):

{
  "ERR_CODE": 0,
  "ERR_MESSAGE": "No error",
  "LOC": {
    "column1": "abc",
    "column2": "123",
    "column3": "def"
  },
  {
    "column1": "abc",
    "column2": "123",
    "column3": "def"
  }
}

我根据 [0:] 的解决方案进行了更改,因为它给了我这个:

{
  "ERR_CODE": 0,
  "ERR_MESSAGE": "No error",
  "LOC": [                    # list
  {
    "column1": "abc",
    "column2": "123",
    "column3": "def"
  },
  {
    "column1": "abc",
    "column2": "123",
    "column3": "def"
  }
 ]                           #list
}

我不希望结果中出现[ ]

【问题讨论】:

  • 你的意思是你不想要[]?
  • 如果有多个子对象,您的预期结果是什么?
  • 我猜不是列表形式@RajithThennakoon
  • 我向你展示了我对多个孩子的预期结果@RajithThennakoon
  • 你不能像这样创建对象` "LOC": { "column1": "abc", "column2": "123", "column3": "def" }, { "column1 ": "abc", "column2": "123", "column3": "def" }` .如果你有多个子对象,它应该在一个列表中,或者你必须创建新的键值对。跨度>

标签: python dataframe dictionary


【解决方案1】:

您可以将记录作为列表分配返回

result = list(result.to_dict("index").values())

【讨论】:

    猜你喜欢
    • 2022-07-05
    • 2019-04-21
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2021-06-19
    • 2017-03-22
    • 2019-07-18
    相关资源
    最近更新 更多