python数据帧获取特定单词
数据帧如下所示:python数据帧获取特定单词,python,apply,Python,Apply,数据帧如下所示: stop_wd=['the','a'] df2=pandas.DataFrame({'col1':[1,3,4], 'col2':['the future','a dog','data frame']}) df2 col1 col2 0 1 the future 1 3 a dog 2 4 data frame 我想要得到的结果是: col1 col2 0 1 future 1
stop_wd=['the','a']
df2=pandas.DataFrame({'col1':[1,3,4],
'col2':['the future','a dog','data frame']})
df2
col1 col2
0 1 the future
1 3 a dog
2 4 data frame
我想要得到的结果是:
col1 col2
0 1 future
1 3 dog
2 4 data frame
stop\u wd=['the','a']
因此未来的应该删除the
。a狗
应该移除a
。数据框
不删除任何内容
我尝试使用应用:
def word(x,stop_wd=stop_wd):
for r in stop_wd:
if r in x.split():
x=x.split(' ').remove(r)
return x
else:
return x
df2.col2=df2.col2.apply(word)
但这不起作用。我只得到这个结果:
col1 col2
0 1 None
1 3 a dog
2 4 data frame
在尝试所有可能性之前,您的外观就会终止
import pandas
stop_wd=['the','a']
df2=pandas.DataFrame({'col1':[1,3,4],
'col2':['the future','a dog','data frame']})
def word(x,stop_wd=stop_wd):
for r in stop_wd:
if r in x.split():
x=x.replace(r,'')
return x
df2.col2=df2.col2.apply(word)
产量
future
dog
data frame
这就是我认为您正在寻找的在尝试所有可能性之前,您的外观就会终止
import pandas
stop_wd=['the','a']
df2=pandas.DataFrame({'col1':[1,3,4],
'col2':['the future','a dog','data frame']})
def word(x,stop_wd=stop_wd):
for r in stop_wd:
if r in x.split():
x=x.replace(r,'')
return x
df2.col2=df2.col2.apply(word)
产量
future
dog
data frame
这就是我认为您正在寻找的您的答案就在那里-您的word
功能只是稍微有点错误
我会使用列表理解,它非常容易阅读,并且具有只拆分文本一次的优点(在您的解决方案中,您对停止列表中的每个单词调用.split()
)
您的答案几乎就在那里-您的word
函数只是稍微有点错误
我会使用列表理解,它非常容易阅读,并且具有只拆分文本一次的优点(在您的解决方案中,您对停止列表中的每个单词调用.split()
)
谢谢你的提问。它实际上帮助我学会了如何处理类似的情况。谢谢你的提问。它实际上帮助我学会了如何处理类似的情况。