Python 3 Pandas使用Startswith +或选择Dataframe

时间:2016-10-25 20:29:25

标签: regex python-3.x pandas dataframe startswith

寻找正确的语法来执行str.startswith但我想要多个条件。

工作代码我只返回以字母“N”开头的办公室:

new_df = df[df['Office'].str.startswith("N", na=False)]

寻找返回可以以字母“N”,“M”,“V”或“R”开头的办公室的代码。以下似乎不起作用:

    new_df = df[df['Office'].str.startswith("N|M|V|R", na=False)]

我错过了什么?谢谢!

2 个答案:

答案 0 :(得分:2)

试试这个:

df[df['Office'].str.contains("^(?:N|M|V|R)")]

或:

df[df['Office'].str.contains("^[NMVR]+")]

演示:

In [91]: df
Out[91]:
        Office
0        No-No
1         AAAA
2    MicroHard
3       Valley
4        vvvvv
5   zzzzzzzzzz
6  Risk is fun

In [92]: df[df['Office'].str.contains("^(?:N|M|V|R)")]
Out[92]:
        Office
0        No-No
2    MicroHard
3       Valley
6  Risk is fun

In [93]: df[df['Office'].str.contains("^[NMVR]+")]
Out[93]:
        Office
0        No-No
2    MicroHard
3       Valley
6  Risk is fun

答案 1 :(得分:0)

方法startswith允许将 string tuple 作为其第一个参数:

# Option 1
new_df = df[df['Office'].str.startswith(('N','M','V','R'), na=False)

示例:

df = pd.DataFrame(data=[np.nan, 'Austria', 'Norway', 'Madagascar', 'Romania', 'Spain', 'Uruguay', 'Yemen'], columns=['Office'])
print(df)
df.Office.str.startswith(('N','M','V','R'), na=False)

输出:

       Office
0         NaN
1     Austria
2      Norway
3  Madagascar
4     Romania
5       Spain
6     Uruguay
7       Yemen


0    False
1    False
2     True
3     True
4     True
5    False
6    False
7    False

@MaxU指出的其他选项是:

# Option 2
df[df['Office'].str.contains("^(?:N|M|V|R)")]

# Option 3
df[df['Office'].str.contains("^[NMVR]+")]

性能(非严格测试):

from datetime import datetime

n = 100000

start_time = datetime.now()
for i in range(n):
    df['Office'].str.startswith(('N','M','V','R'), na=False)
print ("Option 1: ", datetime.now() - start_time)

start_time = datetime.now()
for i in range(n):
    df['Office'].str.contains("^(?:N|M|V|R)", na=False)
print ("Option 2: ", datetime.now() - start_time)

start_time = datetime.now()
for i in range(n):
    df['Office'].str.contains("^[NMVR]+", na=False)
print ("Option 3: ", datetime.now() - start_time)

结果:

Option 1:  0:00:22.952533
Option 2:  0:00:23.502708
Option 3:  0:00:23.733182

最终选择:时间差异不大,所以由于sintax更简单且性能更好,因此我选择选项1