loc中的數據是列名,是字符串,所以前后都要??;iloc中數據是int整型,所以是Python默認的前閉后開
一、loc函數
構建數據集df
import pandas as pd
df = pd.DataFrame([
['green', 'M', 10.1, 'class1'],
['red', 'L', 13.5, 'class2'],
['blue', 'XL', 15.3, 'class1']])
print (df)
# 數據集為以下內容,所有操作均對df進行
0 1 2 3
0 green M 10.1 class1
1 red L 13.5 class2
2 blue XL 15.3 class1
loc函數主要通過行標簽索引行數據,劃重點,標簽!標簽!標簽!
loc[1] 選擇行標簽是1的(從0、1、2、3這幾個行標簽中)
In[1]: df.loc[1]
Out[1]:
0 red
1 L
2 13.5
3 class2
loc[0:1] 和 loc[0,1]的區別,其實最重要的是loc[0:1]和iloc[0:1]
In[10]: df.loc[0:1] #取第一和第二行,loc[]中的數字其實是行索引,所以算是前閉加后閉
Out[10]:
0 1 2 3
0 green M 10.1 class1
1 red L 13.5 class2
In[12]: df.iloc[0:1]
Out[12]:
0 1 2 3
0 green M 10.1 class1
In[11]: df.loc[0,1]
Out[11]: 'M'
索引某一列數據,loc[:,0:1],還是標簽,注意,如果列標簽是個字符,比如'a',loc['a']是不行的,必須為loc[:,'a']。
但如果行標簽是'a',選取這一行,用loc['a']是可以的。
n[13]: df.loc[:,0:1]
Out[13]:
0 1
0 green M
1 red L
2 blue XL
二、iloc函數
iloc 主要是通過行號獲取行數據,劃重點,序號!序號!序號!
iloc[0:1],由于Python默認是前閉后開,所以,這個選擇的只有第一行!
In[12]: df.iloc[0:1]
Out[12]:
0 1 2 3
0 green M 10.1 class1
如果想用標簽索引,如iloc['a'],就會報錯,它只支持int型。
三、ix函數
ix——結合前兩種的混合索引,即可以是行序號,也可以是行標簽。
另,一些篩選操作
如選擇prize>10(prize為一個標簽)的,即 df.loc[df.prize>10]
還有&并或等操作