LOC和ILOC以及XI的區別

2021-08-03 23:57:08 字數 2870 閱讀 1348

loc——通過行標籤索引行資料

1.1 loc[1]表示索引的是第1行(index 是整數)

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [0,1]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.loc[1]

」」』

a 4

b 5

c 6

」』 1.2 loc[『d』]表示索引的是第』d』行(index 是字元)

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [『d』,』e』]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.loc[『d』]

」」』

a 1

b 2

c 3

」』 1.3 如果想索引列資料,像這樣做會報錯

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [『d』,』e』]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.loc[『a』]

」」』

keyerror: 『the label [a] is not in the [index]』

」』 1.4 loc可以獲取多行資料

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [『d』,』e』]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.loc[『d』:]

」」』

a b c

d 1 2 3

e 4 5 6

」』 1.5 loc擴充套件——索引某行某列

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [『d』,』e』]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.loc[『d』,[『b』,』c』]]

」」』

b 2

c 3

」』 1,6 loc擴充套件——索引某列

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [『d』,』e』]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.loc[:,[『c』]]

」」』

c d 3

e 6

」』 當然獲取某列資料最直接的方式是df.[列標籤],但是當列標籤未知時可以通過這種方式獲取列資料。

需要注意的是,dataframe的索引[1:3]是包含1,2,3的,與平時的不同。

2. iloc——通過行號獲取行資料

2.1 想要獲取哪一行就輸入該行數字

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [『d』,』e』]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.loc[1]

」」』

a 4

b 5

c 6

」』 2.2 通過行標籤索引會報錯

[python] view plain copy

print?

import pandas as pd

data = [[1,2,3],[4,5,6]]

index = [『d』,』e』]

columns=[『a』,』b』,』c』]

df = pd.dataframe(data=data, index=index, columns=columns)

print df.iloc[『a』]

」」』

typeerror: cannot do label indexing on

loc 和 iloc基本選取操作

import pandas as pd loc 和 iloc基本選取操作 df pd.dataframe hu 男 23 chen 女 27 li 男 33 index 1001 1002 1003 columns name age loc選取行列和相應的資料型別,loc注意要用於標籤索引選取 一,...

pandas中loc和iloc方法

我們建立乙個dataframe import numpy as np import pandas as pd df pd.dataframe np.arange 16 reshape 4,4 index list abcd columns list abcd in df out a b c d a ...

pandas的索引問題(iloc和loc)

loc指的是定位索引,英文意思是loction iloc指的是數字定位索引,int location表示這個只能通過整數索引來取出元素 取出指定的某幾行,或某幾列 這個方法是在需要取出特定的行或者列的時候用,行或者列可以不填,預設選擇是全部行或者全部列 區域選擇 這個方法是比較常用的選擇子區域的方法...