在进行数据分析前,我们一般都需要从源数据中筛选出自己需要的部分,在这个步骤比较常用的就是 Pandas 中的 loc 函数和 iloc 函数,所以本文老王就介绍下这个函数并分享 5 个常见的用法。
一、函数介绍
1、loc 函数
python 官网介绍:
Access a group of rows and columns by label(s) or a boolean array.
.loc[] is primarily label based, but may also be used with a boolean array.
Allowed inputs are:
- A single label, e.g.
5or'a', (note that5is interpreted as a label of the index, and never as an integer position along the index). - A list or array of labels, e.g.
['a', 'b', 'c']. - A slice object with labels, e.g.
'a':'f'. Warning: Note that contrary to usual python slices, both the start and the stop are included - A boolean array of the same length as the axis being sliced, e.g.
[True, False, True]. - A
callablefunction with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)
简而言之:loc 函数通过行列名或者判断条件来取符合条件的行列。
2、iloc 函数
python 官网介绍:
Purely integer-location based indexing for selection by position.
.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.
Allowed inputs are:
- An integer, e.g.
5. - A list or array of integers, e.g.
[4, 3, 0]. - A slice object with ints, e.g.
1:7. - A boolean array.
- A
callablefunction with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don’t have a reference to the calling object, but would like to base your selection on some value.
简而言之:iloc 通过行列号来取值。
二、函数用法实例
下面是 5 个经常用到的方式的代码实例:
1. 利用 loc、iloc 提取行数据
import numpy as np
import pandas as pd
#创建一个Dataframe
data=pd.DataFrame(np.arange(16).reshape(4,4),index=list('abcd'),columns=list('ABCD'))
In[1]: data
Out[1]:
A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
#取索引为'a'的行
In[2]: data.loc['a']
Out[2]:
A 0
B 1
C 2
D 3
#取第一行数据,索引为'a'的行就是第一行,所以结果相同
In[3]: data.iloc[0]
Out[3]:
A 0
B 1
C 2
D 3
2. 利用 loc、iloc 提取列数据
In[4]:data.loc[:,['A']] #取'A'列所有行,多取几列格式为 data.loc[:,['A','B']]
Out[4]:
A
a 0
b 4
c 8
d 12
In[5]:data.iloc[:,[0]] #取第0列所有行,多取几列格式为 data.iloc[:,[0,1]]
Out[5]:
A
a 0
b 4
c 8
d 12
3. 利用 loc、iloc 提取指定行、指定列数据
In[6]:data.loc[['a','b'],['A','B']] #提取index为'a','b',列名为'A','B'中的数据 Out[6]: A B a 0 1 b 4 5 In[7]:data.iloc[[0,1],[0,1]] #提取第0、1行,第0、1列中的数据 Out[7]: A B a 0 1 b 4 5
4. 利用 loc、iloc 提取所有数据
In[8]:data.loc[:,:] #取A,B,C,D列的所有行
Out[8]:
A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
In[9]:data.iloc[:,:] #取第0,1,2,3列的所有行
Out[9]:
A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
5. 利用 loc 函数,根据某个数据来提取数据所在的行
In[10]: data.loc[data['A']==0] #提取data数据(筛选条件: A列中数字为0所在的行数据) Out[10]: A B C D a 0 1 2 3 In[11]: data.loc[(data['A']==0)&(data['B']==2)] #提取data数据(多个筛选条件) Out[11]: A B C D a 0 1 2 3
利用 loc 函数的时候,当 index 相同时,会将相同的 index 全部提取出来,
- 优点是:如果 index 是人名,数据框为所有人的数据,那么我可以将某个人的多条数据提取出来分析;
- 缺点是:如果 index 不具有特定意义,而且重复,那么提取的数据需要进一步处理,可用 .reset_index() 函数重置 index
以上实例来自:https://blog.csdn.net/W_weiying/article/details/81411257






