pandas 数据框提取字符串

pandas dataframe extract strings

我的数据框有一个名为 'a' 的列,它可能包含 'apple' 和 'orange'。我想要的是提取它们(如果它们存在),否则标记为 'others'.

我可以简单地遍历行并提取它们。但是,我看到一些 numpy.where() 用于类似目的的用法,但只有两类。

result = numpy.where(df['a'].str.contains('apple'), 'apple', 'others')

3类的情况可以套用到这里吗?换句话说,result 应该包含 'apple'、'orange' 或 'others' 的条目。

有没有比简单循环更好的方法?

使用str.extract with fillna:

df = pd.DataFrame({'a': ['orange','apple','a']})
print (df)
        a
0  orange
1   apple
2       a

df['new'] = df.a.str.extract('(orange|apple)', expand=False).fillna('others')
print (df)
        a     new
0  orange  orange
1   apple   apple
2       a  others

只需使用 np.in1d 查找 applemango 的项目来创建一个布尔掩码,然后可以将其与 np.where 一起使用来设置其余项目作为 others。因此,我们将有 -

df['b'] = np.where(np.in1d(df.a,['apple','orange']),df.a,'others')

如果您可能希望使用将这些名称作为较大字符串的一部分的字符串,则可以使用 str.extract(从 中汲取了这个想法,希望没关系! ) 然后使用 np.where,像这样 -

strings = df.a.str.extract('(orange|apple)')
df['b'] = np.where(np.in1d(strings,['apple','orange']),strings,'others')

样本运行-

In [294]: df
Out[294]: 
             a
0  apple-shake
1       orange
2  apple-juice
3        apple
4        mango
5       orange
6       banana

In [295]: strings = df.a.str.extract('(orange|apple)')

In [296]: df['b'] = np.where(np.in1d(strings,['apple','orange']),strings,'others')

In [297]: df
Out[297]: 
             a       b
0  apple-shake   apple
1       orange  orange
2  apple-juice   apple
3        apple   apple
4        mango  others
5       orange  orange
6       banana  others