我有一个这样的数据框:
我想对句子是否包含cat
或dog
或None
进行分类。
df = pd.DataFrame({'comment': ['this is a dog', 'beautiful dog', 'nice cat!', 'this is a tree']})
如何创建一个名为“label”并具有以下值的新列?
df['label'] = ['dog','dog','cat', None]
要求的输出:
comment label
0 this is a dog dog
1 beautiful dog dog
2 nice cat! cat
3 this is a tree None
最佳答案
这是一种方法findall
df['label'] = df.comment.str.findall('|'.join(['cat','dog'])).str[0]
Out[10]:
0 dog
1 dog
2 cat
3 NaN
Name: comment, dtype: object
或者
r='(cat|dog)'
df['label'] = df.comment.str.extract(r)
关于python - 如何使用 Pandas 数据框另一列的句子部分创建新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57666649/