首页 > 解决方案 > 解析列中的字典时,字符串索引必须是整数

问题描述

我在尝试拆分电影数据集(csv 文件)时遇到了一些问题,其中流派列填充了字典类型,例如 [{"id": 28, "name": "Action"}, {" id”:12,“名称”:“冒险”},...]。我正在尝试获取所有“名称”值。我也搜索过这个,但不知道如何正确修复它。有没有人对此有解决方案。

import pandas
import numpy
import json
import matplotlib.pyplot

data = pandas.read_csv('Downloads/tmdb_5000_movies.csv')

def pipe_flatten_names(k):                 
    return '|'.join([x["name"] for x in k])
data['genres'] = data['genres'].apply(pipe_flatten_names)

下面是错误的样子

TypeError                                 Traceback (most recent call last)
<ipython-input-22-d02b9c57fd2e> in <module>()
      2 #    return '|'.join([i.get["name"] for i in x])
      3 
----> 4 data['genres'] = data['genres'].apply(pipe_flatten_names)
      5 
      6 liste_genres = set()                               #Combine all the 
genres collected into a list

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
   3190             else:
   3191                 values = self.astype(object).values
-> 3192                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   3193 
   3194         if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

<ipython-input-21-6b978a26968e> in pipe_flatten_names(k)
      1 def abc(k):
      2     ds = (x["name"] for x in k)#Function collect genres name from Genres column
----> 3     return '|'.join(ds)

<ipython-input-21-6b978a26968e> in <genexpr>(.0)
  1 def pipe_flatten_names(k):
----> 2     ds = (x["name"] for x in k)#Function collect genres name from Genres column
  3     return '|'.join(ds)

TypeError: string indices must be integers

标签: pythondictionarytypeerror

解决方案


当您调用 Apply 方法时,作为参数传递的函数将为包含在用于调用函数 Apply 的 CSV 的特定列中的每个数据调用一次,它的参数是数据本身。例如:

如果我的 CSV 看起来像:

+-----+-----------+
|  id |      name |
+-----+-----------+
|   1 |    Action |
+-----+-----------+
|   2 | Adventure |
+-----+-----------+

在每次调用您的函数时,日期将作为字符串传递,所以如果我调用

x["name"].Apply(func)

func 将被调用 2 次,参数 Action 和 Adventure 作为字符串,并且您是字符串来迭代此字符串 ( k) 将字符串作为索引传递,因此出现错误。如果我理解正确,您的 CSV 文件代表字典的字符串表示形式,因此您必须使用ast内置库对其进行转换,然后读取字典的每个元素。试试这个:

import pandas
import numpy
import ast
data = pandas.read_csv('Downloads/tmdb_5000_movies.csv', sep=';')

def pipe_flatten_names(k):                 
    genres = ast.literal_eval(k)
    return '|'.join(x['name'] for x in genres)
data['genres'] = data['genres'].apply(pipe_flatten_names)

我还更改了 CSV 文件中的分隔符,因为如果您的 CSV 由“,”分隔,而字典使用“,”,它们会变得混乱,因此请尝试使用 dict 语法中不包含的分隔符


推荐阅读