【问题标题】:How to get values in a column of dictionary-like string?如何在一列类似字典的字符串中获取值?
【发布时间】:2021-01-22 09:45:47
【问题描述】:

我有一个数据框,其列如下所示:

d = {'genres': 
      [ [
          {"id": 10751,"name": "Family"}, 
          {"id": 16, "name": "Animation"}, 
          {"id": 12, "name": "Adventure"},           
          {"id": 35, "name": "Comedy"}],
        [
          {"id": 878, "name": "Science Fiction"}, 
          {"id": 12, "name": "Adventure"}, 
          {"id": 53, "name": "Thriller"}]]}

df_input = pd.DataFrame(data=d)

我需要以下输出:

d = {'genres': 
      [ ["Family", "Animation", "Adventure", "Comedy",],
        ["Science Fiction", "Adventure", "Thriller"]]}

df_output = pd.DataFrame(data=d)

【问题讨论】:

  • 输入是什么,是字典吗?

标签: python pandas string dataframe dictionary


【解决方案1】:

您可以通过Series.apply 中的列表理解从字典中提取值:

df_input['genres'] = df_input['genres'].apply(lambda x:[y['name'] for y in x])
print (df_input)
                                   genres
0  [Family, Animation, Adventure, Comedy]
1  [Science Fiction, Adventure, Thriller]

或者通过嵌套列表理解:

df_input['genres'] = [[y['name'] for y in x] for x in df_input['genres']]

编辑:如果真实数据有刺痛,而不是使用字典:

import json, ast

df_input['genres'] = df_input['genres'].apply(lambda x:[y['name'] for y in ast.literal_eval(x)])

或者:

df_input['genres'] = df_input['genres'].apply(lambda x:[y['name'] for y in json.loads(x)])

【讨论】:

  • 当我将这段代码应用于整个数据集时,我仍然有一个错误(字符串索引必须是整数)
  • 错误 - JSON 对象必须是 str、bytes 或 bytearray,而不是 list。
  • Morevoer - 有些行是空列表 - [],因此 lambda 函数可能不适用于某些行
【解决方案2】:

如果你想用 pandas 做到这一点,可以使用 apply 方法 尝试创建一个函数来为每个元素返回“名称”值,

>>> def getNames(x):
        return [xi["name"] for xi in x]

现在,您需要做的就是将它应用到数据框中的列上,

>>> df = pd.DataFrame(data=d)

>>> d_out = df['genres'].apply(getNames) # This returns the output that you want

>>> df_output = pd.DataFrame(data=d_out, columns=["genres"])

    genres
0  [Family, Animation, Adventure, Comedy]
1  [Science Fiction, Adventure, Thriller]

可能有更短的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 2020-06-28
    • 1970-01-01
    • 2012-03-24
    • 2016-08-20
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多