格式化字符串以迭代数据框
formatting strings to iterate over dataframe
背景:
我有以下代码从列表中创建数据框:
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
方法:
我尝试使用以下代码获得所需的输出:
#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
与 str.extract
结合使用
我们可以在这里使用 Series.str.extract
并将它传递给由 |
分隔的 animal_list
,这是正则表达式中的 or
运算符:
df['Animal'] = df['Text'].str.extract(f"({'|'.join(animal_list)})")
或 如果你有 python < 3.5 你不能使用 f-string
我们可以使用评论中@Mike 的回答
df['Animal'] = df['Animal'].str.extract(r"({})".format("|".join(animal_list)))
输出
Text Animal
0 the cat meows cat
1 the dog barks dog
2 the bird chirps bird
用str.split
得到中间词
df['Animal'] = df['Text'].str.split().str[1]
输出
Text Animal
0 the cat meows cat
1 the dog barks dog
2 the bird chirps bird
背景:
我有以下代码从列表中创建数据框:
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
方法:
我尝试使用以下代码获得所需的输出:
#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
与 str.extract
结合使用
我们可以在这里使用 Series.str.extract
并将它传递给由 |
分隔的 animal_list
,这是正则表达式中的 or
运算符:
df['Animal'] = df['Text'].str.extract(f"({'|'.join(animal_list)})")
或 如果你有 python < 3.5 你不能使用 f-string
我们可以使用评论中@Mike 的回答
df['Animal'] = df['Animal'].str.extract(r"({})".format("|".join(animal_list)))
输出
Text Animal
0 the cat meows cat
1 the dog barks dog
2 the bird chirps bird
用str.split
得到中间词
df['Animal'] = df['Text'].str.split().str[1]
输出
Text Animal
0 the cat meows cat
1 the dog barks dog
2 the bird chirps bird