部分字符串匹配时字符串提取-熊猫

时间:2019-06-11 14:25:57

标签: python pandas

让我们考虑以下数据帧:

df=pd.DataFrame({'colA':['1234_usa_Name1_xyz','9876_usa_Abc Name2',
                     '123>>usa>>Name3_xyz','123>>abc_usa>>Name4']})

以及以下列表:

l=['abc name1','abc Name2','Name3',"Name4"]


我正在尝试从colA系列中提取名称(不区分大小写),并准确返回系列中的内容->(大小写必须与系列中的相同)。 我尝试过:

p=r'({})'.format("|".join([i.title() for i in l]))
#"(Abc Name1|Abc Name2|Name3|Name4)"
df.colA.str.extract(p,expand=False)

哪个给我:

[NaN, 'Abc Name2', 'Name3', 'Name4']

预期:

['Name1','Abc Name2','Name3','Name4']

我还尝试了将列表和序列都转换为lower(),但这并没有在输出中保留大小写。

series.str.extract()中的flags参数可以帮助我吗?似乎无法解决这个问题。

感谢我得到的所有帮助。

3 个答案:

答案 0 :(得分:1)

abc name1被完全比较为一个字符串,
 如果是第一个元素,则包含usa_Name1,它不是以abc开头。因此abc name1作为完整字符串不匹配。

相反,您可以做的就是将字符串拆分成单词,然后与|(管道)连接。

l = map(lambda x: "|".join(x.split(" ")), l)

答案 1 :(得分:1)

如果 partially 表示部分单词,请将re.findallpd.Series.apply结合使用:

import re
p=r'({})'.format("|".join([i.title() for i in l])).replace(' ', '|')
df['colA'].apply(lambda x: ' '.join(re.findall(p, x)))

输出:

0        Name1
1    Abc Name2
2        Name3
3        Name4
Name: colA, dtype: object

答案 2 :(得分:1)

效率不是很高,但是您可以将完整匹配的返回优先于部分匹配,同时通过将过程分为几步来保留不区分大小写的匹配。首先提取所有完全匹配,然后提取所有部分匹配,然后将结果合并为一系列,其中仅在没有完全匹配时才使用部分匹配。

export default class DemoApp extends React.Component {

  calendarComponentRef = React.createRef()
  state = {
    calendarWeekends: true,
    calendarEvents: [ // initial event data
      { title: 'Event Now', start: new Date() }
    ]
  }

  render() {
    return (
      <div className='demo-app'>
        <div className='demo-app-top'>
          <button onClick={ this.toggleWeekends }>toggle weekends</button>&nbsp;
          <button onClick={ this.gotoPast }>go to a date in the past</button>&nbsp;
          (also, click a date/time to add an event)
        </div>
        <div className='demo-app-calendar'>
          <FullCalendar
            customButtons: {
                myCustomButton: {
                    text: 'custom!',
                    click: function() {
                        alert('clicked the custom button!');
                        }
                    }
            },
            defaultView="dayGridMonth"
            header={{
              left: 'prev,next today',
              center: 'title, myCustomButton'
              right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
            }}
            plugins={[ dayGridPlugin, timeGridPlugin, interactionPlugin ]}
            ref={ this.calendarComponentRef }
            weekends={ this.state.calendarWeekends }
            events={ this.state.calendarEvents }
            dateClick={ this.handleDateClick }
            />
        </div>
      </div>
    )
  }