这是我的数据集
tweet | url
-----------------------------------|------------------
"Hello World url1 url12" | [url1, url12]
"Good morning url2 engine url41" | [url2, url41]
"Nice to meet you url3 " | [url3]
"You are fantastic " | []
<> >请考虑URL1、URL2…是真实URL的表示形式我想遍历列url,在“tweet”的相应行中查找这些url,然后从我的列tweet中删除所有url,并创建一个新的干净列
起初,我尝试使用此代码
ds['urls_free_tweet'] = ds.apply(lambda row : row['tweet'].replace(str(row['url']), ''), axis=1)
但是这段代码没有考虑列“url”数组中给出的所有url
预期结果
tweet | url | urls_free_tweet
-----------------------------------|----------------------|---------------------
"Hello World url1 url12" | [url1, url12] | "Hello World
"Good morning url2 engine url41" | [url2, url41] | "Good morning engine"
"Nice to meet you url3 " | [url3] | "Nice to meet you"
"You are fantastic " | [] | "You are fantastic "
您可以将列表作为带有
|
符号的字符串连接起来,并用re.sub
替换逐行,因为您需要将每列的每一行中的值相互比较。要进行矢量化,只有当您可以拥有整个数据帧的所有URL的列表并以这种方式一次替换所有URL时,它才会起作用,但我不确定这是否是什么——因此可能需要逐行比较:输入:
代码:
输出:
如果希望
url
在末尾作为列表返回,则可以执行df['url'] = df['url'].str.split('|')
目前还不清楚您的数据是否以列表、数据帧或其他形式出现。因此,我将向您展示一个解决方案,该解决方案可以用于任何一种情况,只需对数据进行迭代,并在每次对数据进行迭代时使用以下逻辑。用当前迭代的数据值替换str和url变量
我认为它可以简单化如下:
或
相关问题 更多 >
编程相关推荐