本文轉載自https://blog.csdn.net/W_weiying/article/details/81411257#commentBox
loc函數:通過行索引 “Index” 中的具體值來取行數據(如取"Index"爲"A"的行)
iloc函數:通過行號來取行數據(如取第二行的數據)
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