【发布时间】:2019-11-30 16:07:09
【问题描述】:
我有一个名为 result 的数据框:
result.head(5)
Out[60]:
Product_name metadata \
0 like minds {'Title': 'Like Minds', 'Year': '2006', 'Rated...
1 16 years of alcohol {'Title': '16 Years of Alcohol', 'Year': '2003...
2 grimm {'Title': 'Grimm', 'Year': '2011–2017', 'Rated...
4 gisaku {'Title': 'Gisaku', 'Year': '2005', 'Rated': '...
5 deadly cargo {'Title': 'Tarantulas: The Deadly Cargo', 'Yea...
Year Rated
0 1900 U
1 1900 U
2 1900 U
4 1900 U
5 1900 U
我正在使用一个名为 extract_info 的函数来分隔元数据列中的各个字段,其每个元素都是一个字典。
def extract_info(info_dict):
return (info_dict['Year'], info_dict['Rated'])
元数据列元素不知何故被解释为字符串序列。无法理解为什么会这样?
result['Year'], result['Rated'] = result['metadata'].apply(lambda x : extract_info(x))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-63-70a1390b0278> in <module>
----> 1 result['Year'], result['Rated'] = result['metadata'].apply(lambda x : extract_info(x) )
//anaconda3/lib/python3.7/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
3589 else:
3590 values = self.astype(object).values
-> 3591 mapped = lib.map_infer(values, f, convert=convert_dtype)
3592
3593 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-63-70a1390b0278> in <lambda>(x)
----> 1 result['Year'], result['Rated'] = result['metadata'].apply(lambda x : extract_info(x) )
<ipython-input-61-95b953ff8485> in extract_info(info_dict)
1 def extract_info(info_dict):
----> 2 return (info_dict['Year'], info_dict['Rated'])
3
TypeError: string indices must be integers
我该怎么做?
【问题讨论】:
标签: python-3.x pandas dataframe lambda