我正在用pandas处理xlsx文件,如果前一列包含bodypart预定义列表中的单词,我想在列中添加单词“bodypart”。在
原始数据帧:
Sentence Type
my hand NaN
the fish NaN
结果数据帧:
^{pr2}$我试过的都没用。我觉得我错过了一些很明显的东西。这是我最后一次(失败的)尝试:
import pandas as pd
import numpy as np
bodyparts = ['lip ', 'lips ', 'foot ', 'feet ', 'heel ', 'heels ', 'hand ', 'hands ']
df = pd.read_excel(file)
for word in bodyparts :
if word in df["Sentence"] : df["Type"] = df["Type"].replace(np.nan, "bodypart", regex = True)
我也尝试了这个方法,用as变体“NaN”和NaN作为结构更换公司名称:
if word in df['Sentence'] : df["Type"] = df["Type"].str.replace("", "bodypart")
任何帮助将不胜感激!在
您可以创建一个正则表达式来搜索单词边界,然后将其用作
str.contains
的参数,例如:给你:
^{pr2}$肮脏的解决方案是检查两个集合的交集。在
集合A是你身体部分的列表,集合B是句子中的单词集合
最简单的方法是:
在必须放弃
^{pr2}$bodyparts
中的空间之前:df.Sentence.isin(bodyparts)
选择好的行,Type
要设置的列。.loc
是允许修改的索引器。在相关问题 更多 >
编程相关推荐