欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python iloc和loc切片的實現(xiàn)

 更新時間:2022年05月30日 10:10:12   作者:溫欣'  
本文主要介紹了python iloc和loc切片的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

一、含正負號的下標

在這里插入圖片描述

正下標從0開始,負下標從-1開始1。切片的時候包括頭不包括尾部。

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

二、loc和iloc

loc是指location的意思,iloc中的i是指integer。

【1】iloc:根據(jù)標簽的所在位置,從0開始計數(shù),先選取行再選取列

【2】loc:根據(jù)DataFrame的具體標簽選取行列,同樣是先行標簽,后列標簽

在這里插入圖片描述

由上圖可以看出:iloc[:4,2]和loc[:4,2]是不一樣的,前者不包括4,后者包括4

lypdfdata=lypdf.iloc[:,1:-1].values
lypdftarget=lypdf.iloc[:,:-1].values
# 逗號前面是屬于行,后面是屬于列

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

1. 利用loc、iloc提取行數(shù)據(jù)

import numpy as np
import pandas as pd
#創(chuàng)建一個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
 
#取第一行數(shù)據(jù),索引為'a'的行就是第一行,所以結(jié)果相同
In[3]: data.iloc[0]
Out[3]:
A    0
B    1
C    2
D    3

2. 利用loc、iloc提取列數(shù)據(jù)

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提取指定行、指定列數(shù)據(jù)

In[6]:data.loc[['a','b'],['A','B']] #提取index為'a','b',列名為'A','B'中的數(shù)據(jù)
Out[6]: 
   A  B
a  0  1
b  4  5
 
In[7]:data.iloc[[0,1],[0,1]] #提取第0、1行,第0、1列中的數(shù)據(jù)
Out[7]: 
   A  B
a  0  1
b  4  5

4.利用loc、iloc提取所有數(shù)據(jù)

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函數(shù),根據(jù)某個數(shù)據(jù)來提取數(shù)據(jù)所在的行

In[10]: data.loc[data['A']==0] #提取data數(shù)據(jù)(篩選條件: A列中數(shù)字為0所在的行數(shù)據(jù))
Out[10]: 
   A  B  C  D
a  0  1  2  3
 
In[11]: data.loc[(data['A']==0)&(data['B']==2)] #提取data數(shù)據(jù)(多個篩選條件)
Out[11]: 
   A  B  C  D
a  0  1  2  3

到此這篇關于python iloc和loc切片的實現(xiàn)的文章就介紹到這了,更多相關python iloc和loc切片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論