如何在'text'之前和之后获得第一个单词



我是在v和'v'之后的第一个单词之后。

df = pd.DataFrame({'text': ["cans choc v macroni ice", 
                            "chocolate sundaes v chocolate ice cream", 
                            "Chocolate v sauce"]})

我有一个看起来像:

的数据框架
cans choc v macroni ice
chocolate sundaes v chocolate ice cream
Chocolate v sauce

我希望它看起来像:

cans v macroni
chocolate v chocolate
Chocolate v sauce

在熊猫中如何实现?共同元素是" v"。

您可以使用正则表达式,如@James所建议。但这是使用pandas apply的另一种方法,它更一般地处理了手头的问题。

(顺便说一句,有几个非常相似的问题和答案,例如这个。)

>>> def my_fun(my_text, my_sep):
>>>   vals = my_text.split(my_sep)
>>>   vals = [val.split()[0] for val in vals]
>>>   return vals
>>> df.text.apply(lambda my_text: my_fun(my_text, 'v'))

当然,请使用比这更好的名字!: - )

是否有一个原因您无法使用拆分函数,然后将函数映射到列?

根据第一个示例,这将起作用:

def word_scrape(whole_string):
    outside_v = whole_string.split(" v ")
    first_word = outside_v[0].split(" ")[0]
    last_word = outside_v[1].split(" ")[1]
    return first_word + " v " + last_word
for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)

单词条目的容错容忍度,请使用:

def word_scrape(whole_string):
    try:
        outside_v = whole_string.split(" v ")
        first_word = outside_v[0].split(" ")[0]
        last_word = outside_v[1].split(" ")[1]
        return first_word + " v " + last_word
    except: 
        outside_v = whole_string.split(" v ")
        first_word = outside_v[0].split(" ")[0]
        last_word = outside_v[1].split(" ")[0]
        return first_word + " v " + last_word
for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)

根据第二个示例,这将起作用:

def word_scrape(whole_string):
    outside_v = whole_string.split(" v ")
    first_word = outside_v[0].split(" ")[0]
    last_word = outside_v[1].split(" ")[0]
    return first_word + " v " + last_word
for i,text in enumerate(df.ix[:,'text']):
    df.ix[i,'text'] = word_scrape(text)

让我们尝试一下:

df.text.str.split('v', expand=True)
  .apply(lambda x: x.str.extract('(w+)', expand=False))
  .apply(lambda x: ' v '.join(x), 1)

输出:

0           cans v macroni
1    chocolate v chocolate
2        Chocolate v sauce

您可以将正则表达式传递给text列上的字符串操作。

df.text.str.extract(r'(w+ v w+)', expand=True)
# returns:
                     0
0       choc v macroni
1  sundaes v chocolate
2    Chocolate v sauce

最新更新