enter image description here我只需要从字符串中选择名称。
train["collectionName"]=train["belongs_to_collection"].apply(lambda x : x[0]["name"] if x!={} else 0)
但是它会引发类似
的错误TypeError:字符串索引必须为整数
我希望我的结果像
中只有name
部电影一样
[
{
'id': 313576,
'name': 'Hot Tub Time Machine Collection',
'poster_path': '/iEhb00TGPucF0b4joM1ieyY026U.jpg',
'backdrop_path': '/noeTVcgpBiD48fDjFVic1Vz7ope.jpg'
}
]
仅值而不是键
TypeError跟踪(最近一次通话) 在 ----> 1列火车[“ collectionName”] =火车[“ belongs_to_collection”]。apply(lambda x:x [0] [“ name”]如果x!= {}否则为0)
D:apply(self,func,convert_dtype,args,** kwds)中的D:\ anaconda3 \ lib \ site-packages \ pandas \ core \ series.py 3589其他: 3590个值= self.astype(object).values -> 3591映射= lib.map_infer(值,f,convert = convert_dtype) 3592 3593 if len(mapped)and isinstance(mapped [0],Series):
pandas._libs.lib.map_infer()中的pandas / _libs / lib.pyx
在(x)中 ----> 1列火车[“ collectionName”] =火车[“ belongs_to_collection”]。apply(lambda x:x [0] [“ name”]如果x!= {}否则为0)
TypeError:字符串索引必须为整数
答案 0 :(得分:0)
这可能对您有用:
>>> a = [{'id': 313576, 'name': 'Hot Tub Time Machine Collection', 'poster_path': '/iEhb00TGPucF0b4joM1ieyY026U.jpg', 'backdrop_path': '/noeTVcgpBiD48fDjFVic1Vz7ope.jpg'}]
>>> names = [i['name'] for i in a]
>>> names
['Hot Tub Time Machine Collection']
>>>