【问题标题】:How do I create a list of values of a list of dictionaries in a dataframe?如何在数据框中创建字典列表的值列表?
【发布时间】:2019-08-26 19:12:22
【问题描述】:

我有一个数据框,每个单元格内都有一个字典列表。我正在尝试将字典的值提取为同一数据框的新列中的列表

我当前的数据框如下所示:

id             tags         
1         [{'tag':'happy'},
           {'tag':'sad'},
           {'tag':'ok'}]

2         [{'tag':'ok'},
           {'tag':'angry'},
           {'tag':'mad'}]

3         [{'tag':'content'},
           {'tag':'very mad'},
           {'tag':'alright'}]

我想要的数据框:

id           tags_new
1         ['happy', 'sad', 'ok']
2         ['ok', 'angry', 'mad']
3         ['content', 'very mad', alright']

我尝试了几个选项。

首先,我试过了:

Return a list of values of dictionaries inside a list

df=["tags"] = [y for x in df["tags"] for y in x.values()]

...这给了我:

SyntaxError: can't assign to literal

第二,我试过了:

df["tags"] = [x in ["tag"] for x in df["tags"]]

...返回布尔值。

有什么建议吗?这似乎需要快速修复,但它让我很难过。

【问题讨论】:

    标签: python-3.x list dataframe dictionary


    【解决方案1】:

    这样的?

    df = {
      1: [{'tag':'happy'},{'tag':'sad'},{'tag':'ok'}],
      2:[{'tag':'happy'},{'tag':'mad'},{'tag':'ok'}]
      }
    
    for i in df:
      temp = []
      for j in df[i]:
        temp+=[j["tag"]]
      df[i]=temp
    
    print(df)
    

    【讨论】:

    • 我刚试过,它给了我一个“关键错误:0”,专门用于“for j in df[i]:”行
    • 再试一次,我修好了
    • 越来越近了。我收到关于“temp +=”行的“类型错误:字符串索引必须是整数”错误
    • 你的初始字典和我的格式一样吗?
    • 您的格式似乎不同,我的是在数据框中。这有什么不同吗?
    猜你喜欢
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多