python pandas中索引函數(shù)loc和iloc的區(qū)別分析
使用pandas進(jìn)行數(shù)據(jù)分析的時(shí)候,我們經(jīng)常需要對(duì)DataFrame的行或者列進(jìn)行索引。使用pandas進(jìn)行索引的方法主要有三種:直接使用行或者列標(biāo)簽、loc函數(shù)和iloc函數(shù)。
舉個(gè)簡(jiǎn)單的例子:
import numpy as np
import pandas as pd
df = pd.DataFrame({"Fruits":["apple","pear","banana","watermelon"],"Price":[1.2,1.4,2.3,4.2],"Sales":[11,45,25,16]})
df
生成的DataFrame如下所示:
| Fruits | Price | Sales | |
| 0 | apple | 1.2 | 11 |
| 1 | pear | 1.4 | 45 |
| 2 | banana | 2.3 | 25 |
| 3 | watermelon | 4.2 | 16 |
1、直接使用行或者列標(biāo)簽
假如我們要選取df的Fruits和Price兩列,則
df[['Fruits','Price']]
| Fruits | Price | |
| 0 | apple | 1.2 |
| 1 | pear | 1.4 |
| 2 | banana | 2.3 |
| 3 | watermelon | 4.2 |
假如我們要選取df的第2、3行,則
df[2:4]
| Fruits | Price | Sales | |
| 2 | banana | 2.3 | 25 |
| 3 | watermelon | 4.2 | 16 |
2、loc函數(shù)
loc函數(shù)是基于行標(biāo)簽和列標(biāo)簽進(jìn)行索引的,其基本用法為:
DataFrame.loc[行標(biāo)簽,列標(biāo)簽]
假如我們要選取df的第2、3行和Price、Sales對(duì)應(yīng)的列,則
df[2:3,'Price':'Sales']
| Price | Sales | |
| 2 | 2.3 | 25 |
| 3 | 4.2 | 16 |
假如我們要選取所有的行和Fruits、Sales對(duì)應(yīng)的列,則
df.loc[:,['Fruits','Sales']]
| Fruits | Sales | |
| 0 | apple | 11 |
| 1 | pear | 45 |
| 2 | banana | 25 |
| 3 | watermelon | 16 |
3、iloc函數(shù)
iloc函數(shù)是基于行和列的位置進(jìn)行索引的,索引值從0開(kāi)始,并且得到的結(jié)果不包括最后一個(gè)位置的值,其基本用法為:
DataFrame.iloc[行位置,列位置]
假如我們要選取df的第2、3行和第1、2列,則
df.iloc[2:4,1:3]
| Price | Sales | |
| 2 | 2.3 | 25 |
| 3 | 4.2 | 16 |
假如我們要選取所有的行和第0、2列,則
df.iloc[:,[0,2]]
| Fruits | Sales | |
| 0 | apple | 11 |
| 1 | pear | 45 |
| 2 | banana | 25 |
| 3 | watermelon | 16 |
總結(jié)
到此這篇關(guān)于python pandas中索引函數(shù)loc和iloc區(qū)別的文章就介紹到這了,更多相關(guān)pandas索引函數(shù)loc和iloc內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信