Python小推车

pandas 数据筛选loc and iloc

2018-12-05  本文已影响48人  Thinkando
In [1]: import numpy as np                                                      

In [2]: import pandas as pd  
In [5]: df=pd.DataFrame({'a':[1,2,3],'b':[3,5,6],'c':[2,4,7]})                  

In [6]: df                                                                      
Out[6]: 
   a  b  c
0  1  3  2
1  2  5  4
2  3  6  7

1. 单条件筛选

In [7]: df[df['a']>2]                                                           
Out[7]: 
   a  b  c
2  3  6  7

In [12]: df[['b','c']][df['a']>2]                                               
Out[12]: 
   b  c
2  6  7

# 定位筛选
In [13]: df[df.a.isin([2,3])]                                                   
Out[13]: 
   a  b  c
1  2  5  4
2  3  6  7

2. 多条件筛选

In [14]: df[(df['a'] >1) & (df['c'] < 7)]                                       
Out[14]: 
   a  b  c
1  2  5  4

# 使用numpy的logical_and函数完成同样的功能
In [16]: df[np.logical_and(df['a']>1,df['b']<7)]                                
Out[16]: 
   a  b  c
1  2  5  4
2  3  6  7

3. 索引

In [18]: df[1:3]                                                                
Out[18]: 
   a  b  c
1  2  5  4
2  3  6  7
In [22]: df[['a','c']]                                                          
Out[22]: 
   a  c
0  1  2
1  2  4
2  3  7

4. loc函数

In [23]: df.loc[1,'c']                                                          
Out[23]: 4

In [24]: df.loc[1:3,['a','c']]                                                  
Out[24]: 
   a  c
1  2  4
2  3  7

In [25]: df.loc[[1,2],['a','c']]                                                
Out[25]: 
   a  c
1  2  4
2  3  7

5. iloc 函数(懒人必备)

In [26]: df.iloc[1,2]                                                           
Out[26]: 4

In [30]: df.iloc[1:3,[0,2]]                                                     
Out[30]: 
   a  c
1  2  4
2  3  7

In [28]: df.iloc[[1,2],[0,2]]                                                   
Out[28]: 
   a  c
1  2  4
2  3  7

6. at函数

In [33]: df.at[1,'a']                                                           
Out[33]: 2

7. iat函数

In [35]: df.iat[1,0]                                                            
Out[35]: 2
上一篇下一篇

猜你喜欢

热点阅读