【问题标题】:Python List/Dataframe to DictPython 列表/数据框到字典
【发布时间】:2019-08-16 02:01:04
【问题描述】:

大家好,我有一个关于将 List/Dataframe 转换为 Dict 的问题。

我目前的数据:

Column header: a
Rows = b , c , d , e

如何将其转换成这种格式的字典?

Keys = rows
Value = a: rows

我有一个列表要做,但我也可以将它转换成数据框来做。

【问题讨论】:

  • 为了给出更好的答案,请提供更多细节。你的数据是什么类型的?字符串、整数、其他?另外,请给出一个更具体的预期结果示例。

标签: python pandas dataframe dictionary


【解决方案1】:

假设你的数据都是字符串:

new_dict = {}
for row in rows:
    new_dict[row] = f'{column_header} {row}'

【讨论】:

    【解决方案2】:
    1. 您可以通过以下示例将列表转换为字典

      示例 1:列表到字典,列表元素作为字典中的键

      list = ["development", "testing", "backend", "frontend"]
      dictionary = {i:5 for i in list}
      

      示例 2:将列表转换为字典,列表元素作为字典中的值

      list = ["development", "testing", "backend", "frontend"]
      dictionary = { i : list[i] for i in range(0, len(list) )}
      
    2. 如果您有如下一组数据框,则可以使用 pandas

      例子:

           0        1           2
      0    Khushi  34      Sydeny
      1   Parnika  30       Delhi
      2  Srinidhi  16    New York
      3    Shobha  30  Washington
      

      例如,上面的数据框存储在名为 dataframe 的变量中,然后我们可以将其转换为字典

      dataframe.to_dict()
      

      输出:

      {0: {0: 'Khushi', 1: 'Parnika', 2: 'Srinidhi', 3: 'Shobha'},
      1: {0: 34, 1: 30, 2: 16, 3: 30},
      2: {0: 'Sydeny', 1: 'Delhi', 2: 'New York', 3: 'Washington'}}
      

    【讨论】:

    • 请提供一些例子。 “你可以使用某些东西”还不够好
    猜你喜欢
    • 2017-03-01
    • 2021-04-10
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2020-12-28
    • 2021-06-26
    • 2021-06-11
    相关资源
    最近更新 更多