2017-02-14 62 views
1

开始选择数据帧行,我有以下数据框df1熊猫:只有在特定的列中的值与

X   Y   A  B 
0 484   408   10  3360 
1 478   415   24  3365 
2 504   452   31  yes 
3 613   551   33  maybe 
4 663   665   39  no 

我知道如何选择该行的哪一列Byes或任何其他特定值:

df1.loc[df1['B'] == 'yes'] 

但我怎么能选择不启动336的所有行?

PS:在我的情况下,33603365是字符串。

回答

4

我会使用类似df[~df.B.str.startswith('336')]的东西,使用str访问器。例如,

>>> df = pd.DataFrame({'B': ['3360', '3365', 'yes', 'maybe', 'no']}) 
>>> df[~df.B.str.startswith('336')] 
     B 
2 yes 
3 maybe 
4  no 

如果你有多个字符串来检查,startswith接受前缀的元组。

>>> df[~df.B.str.startswith(('112', '336', 'n'))] 
     B 
2 yes 
3 maybe 
+0

忘了提。你会如何结合两个或更多的条件,比如'336'和'545'?你可以在accessor中使用'or'吗? – FaCoffee

+1

@ CF84你可以给'startswith'提供一个元组。例如,'df [〜df.B.str.startswith(('112','336','556'))]'。 – miradulo