【问题标题】:formatting strings to iterate over dataframe [duplicate]格式化字符串以迭代数据框[重复]
【发布时间】: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


【解决方案1】:

animal_liststr.extract 一起使用

我们可以在这里使用Series.str.extract 并将animal_list 传递给它,该| 是正则表达式中的or 运算符:

df['Animal'] = df['Text'].str.extract(f"({'|'.join(animal_list)})")

或者如果你有python f-string

我们可以使用来自 cmets 的@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

【讨论】:

  • 狙击我! df['Sound'] = df['Animal'].str.extract(r"({})".format("|".join(animal_list)))
  • 感谢您的补充,并在答案中添加了您的解决方案@Mike
猜你喜欢
  • 1970-01-01
  • 2021-09-29
  • 2020-08-01
  • 1970-01-01
  • 2015-01-07
  • 2011-05-17
  • 2014-09-24
  • 2013-12-10
  • 2012-01-07
相关资源
最近更新 更多