【问题标题】:applying a lambda function on Dataframe giving errors在 Dataframe 上应用 lambda 函数给出错误
【发布时间】: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


    【解决方案1】:

    问题是在应用您的函数之前将列转换为dictionaries,因为strings:

    import ast
    result['Year'], result['Rated'] = result['metadata'].apply(lambda x : extract_info(ast.literal_eval(x)))
    

    【讨论】:

    • 给我“ValueError: malformed node or string”错误。
    • @Sarang - 如果将ast.literal_eval 更改为json.loads 相同的错误?
    • @Sarang - 值也是字符串吗? print (type(result['metadata'].iat[0])) 是字符串吗?
    • json.loads 给出 TypeError: the JSON object must be str, bytes or bytearray, not dict
    • 打印 (type(result['metadata'].iat[0])) :
    猜你喜欢
    • 1970-01-01
    • 2023-01-27
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    相关资源
    最近更新 更多