Python 尝试使用字典和映射转换包含特定文本的行时出现问题
我试图使用字典和map函数重命名数据框中的行。问题是某些行的文本不相同 以下是我的代码:Python 尝试使用字典和映射转换包含特定文本的行时出现问题,python,string,pandas,data-science,Python,String,Pandas,Data Science,我试图使用字典和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
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
再次使用findall和|
再次使用findall和|
试试看-
fb_posts['title'] = fb_posts['title'].apply(converts)
或
您需要将函数对象作为参数传递给应用函数
fb_posts['title'] = fb_posts['title'].apply(converts)
或
您需要将函数对象作为参数传递给应用函数对于少量类别,简单循环可能是有效的:
for x in ['link', 'post', 'status', 'timeline']:
fb_posts.loc[fb_posts['title'].str.contains(x, regex=False), 'title'] = x
正则表达式解决方案也可以工作,但通常在类别较多的情况下效率更高。对于少量类别,简单循环可能更有效:
for x in ['link', 'post', 'status', 'timeline']:
fb_posts.loc[fb_posts['title'].str.contains(x, regex=False), 'title'] = x
正则表达式解决方案也可能有效,但通常在有大量类别的情况下效率更高。还有一个答案
我保留了您的代码,但稍微更改了函数
def converts(row):
for i in ['link', 'post', 'status', 'timeline']:
if i in row['title']:
return i
return row['title']
fb_posts['title'] = fb_posts['title'].apply(lambda x: converts(x), axis=1)
还有一个答案
我保留了您的代码,但稍微更改了函数
def converts(row):
for i in ['link', 'post', 'status', 'timeline']:
if i in row['title']:
return i
return row['title']
fb_posts['title'] = fb_posts['title'].apply(lambda x: converts(x), axis=1)
这可能会起作用,但converts函数有一个语法问题,需要先解决。是的,没有解决and not==这可能会起作用,但转换函数有一个语法问题,需要先解决。是的,没有解决and not==converts使用==比较运算符,您可能打算在其中使用=用于分配converts使用==比较运算符,您可能打算在其中使用=用于分配我收到错误消息“TypeError:得到了一个意外的关键字参数”axis“,这很奇怪;axis是apply的一个参数。你确定你准确地复制了它吗?我收到了错误消息“TypeError:得到了一个意外的关键字参数“axis”,这很奇怪;axis是apply的一个参数。你确定你准确地复制了它?