Skip to main content
 首页 » 编程设计

python之尝试使用字典和 map 转换包含特定文本的行时遇到问题

2025年05月04日24zdz8207

我正在尝试使用字典和 map 函数重命名数据框中的行。问题是某些行没有相同的文本。

这是我的代码:

fb_posts['title'] = fb_posts['title'].astype(str) 
def converts(i): 
  if 'link' in i: 
    i == 'link' 
  elif 'post' in i: 
    i == 'post' 
  elif 'status' in i: 
    i == 'stats' 
  elif 'timeline' in i: 
    i == 'timeline' 
  return i 
fb_posts['title'] = fb_posts['title'].apply(converts(i)) 

所以我首先将列中的所有内容都转换为字符串,这样我就可以找到一个字符串是否包含某个字母并根据是否包含来转换该字符串。

但是这会返回以下回溯:

--------------------------------------------------------------------------- 
ValueError                                Traceback (most recent call last) 
<ipython-input-310-6ddc37cbbb4d> in <module>() 
----> 1 fb_posts['title'] = fb_posts['title'].apply(converts(i)) 
 
/usr/local/lib/python3.6/dist-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds) 
   2532         # if we are a string, try to dispatch 
   2533         if isinstance(func, compat.string_types): 
-> 2534             return self._try_aggregate_string_function(func, *args, **kwds) 
   2535  
   2536         # handle ufuncs and lambdas 
 
/usr/local/lib/python3.6/dist-packages/pandas/core/base.py in _try_aggregate_string_function(self, arg, *args, **kwargs) 
    307             return f(self, *args, **kwargs) 
    308  
--> 309         raise ValueError("{arg} is an unknown string function".format(arg=arg)) 
    310  
    311     def _aggregate(self, arg, *args, **kwargs): 
 
ValueError: Person updated his status. is an unknown string function 

这是我的数据库的示例:

 title    
Person shared a link. 
Person shared a post. 
Person posted on x's timeline 
Person posted on y's timeline 
Person posted on a's timeline 

请您参考如下方法:

对于少量的类别,一个简单的循环可能是有效的:

for x in ['link', 'post', 'status', 'timeline']: 
    fb_posts.loc[fb_posts['title'].str.contains(x, regex=False), 'title'] = x 

正则表达式解决方案也可能有效,但通常在您拥有大量类别时效率更高。