【发布时间】:2019-10-13 10:24:50
【问题描述】:
背景:
我有以下代码可以从列表中创建一个数据框:
l = ['the cat meows',
'the dog barks',
'the bird chirps']
df = pd.DataFrame(l, columns=['Text'])
输出:
Text
0 the cat meows
1 the dog barks
2 the bird chirps
所需的输出:
Text Animal
0 the cat meows cat
1 the dog barks dog
2 the bird chirps bird
方法:
我尝试使用以下代码获取 Desired Output:
#create list of animal names
animal_list = ['cat', 'dog', 'bird']
#extract names from 'Text' column using the names in 'animal_list'
#and create a new column containing extracted 'Text' names
df['Sound'] = df['Animal'].str.extract(r"(%s)"% animal_list)
问题:
但是,当我这样做时,我会得到以下信息:
Text Animal
0 the cat meows t
1 the dog barks t
2 the bird chirps t
问题
如何实现我想要的输出?
【问题讨论】:
-
这里的逻辑是什么。我们需要每次都使用您的
animal_list还是中间词? -
很抱歉,如果不清楚。我的目标如下:1)从“文本”列中提取名称 2)使用“动物列表”中的名称 3)创建一个包含提取的“文本”名称的新列
-
是的,
animal_list中的词是必需的
标签: pandas loops text format special-characters