日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中的ix是啥_详谈Pandas中iloc和loc以及ix的区别

發布時間:2023/12/10 python 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中的ix是啥_详谈Pandas中iloc和loc以及ix的区别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Pandas庫中有iloc和loc以及ix可以用來索引數據,抽取數據。但是方法一多也容易造成混淆。下面將一一來結合代碼說清其中的區別。

1. iloc和loc的區別:

iloc主要使用數字來索引數據,而不能使用字符型的標簽來索引數據。而loc則剛好相反,只能使用字符型標簽來索引數據,不能使用數字來索引數據,不過有特殊情況,當數據框dataframe的行標簽或者列標簽為數字,loc就可以來其來索引。

好,先上代碼,先上行標簽和列標簽都為數字的情況。

import pandas as pd

import numpy as np

a = np.arange(12).reshape(3,4)

print a

>>>

[[ 0 1 2 3]

[ 4 5 6 7]

[ 8 9 10 11]]

df = pd.DataFrame(a)

print df

>>>

0 1 2 3

0 0 1 2 3

1 4 5 6 7

2 8 9 10 11

print df.loc[0]

>>>

0 0

1 1

2 2

3 3

Name: 0, dtype: int32

print df.iloc[0]

0 0

1 1

2 2

3 3

Name: 0, dtype: int32

print df.loc[:,[0,3]]

0 3

0 0 3

1 4 7

2 8 11

print df.iloc[:,[0,3]]

0 3

0 0 3

1 4 7

2 8 11

接下來是把行標簽[0, 1, 2]改成['a', 'b', 'c'],則成這樣了。

df.index = ['a','b','c']

print df

>>>

0 1 2 3

a 0 1 2 3

b 4 5 6 7

c 8 9 10 11

print df.loc[0]

# TypeError: cannot do label indexing on with these indexers [0] of

print df.iloc[0]

>>>

0 0

1 1

2 2

3 3

Name: a, dtype: int32

print df.iloc['a'] # TypeError: cannot do positional indexing on with these indexers [a] of

print df.loc['a'] # 正確

>>>

0 0

1 1

2 2

3 3

Name: a, dtype: int32

同樣地,把列標簽[0, 1, 2, 3]改成['A', 'B, 'C', 'D'],則成這樣了。

df.columns = ['A','B','C','D']

print df

>>>

A B C D

a 0 1 2 3

b 4 5 6 7

c 8 9 10 11

print df.loc[:,'A']

>>>

a 0

b 4

c 8

Name: A, dtype: int32

print df.iloc[:,'A'] # ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types

2.ix是一種混合索引,字符型標簽和整型數據索引都可以。

print df.ix[0]

>>>

A 0

B 1

C 2

D 3

Name: a, dtype: int32

print df.ix['a']

>>>

A 0

B 1

C 2

D 3

Name: a, dtype: int32

print df.ix[:,0]

>>>

a 0

b 4

c 8

Name: A, dtype: int32

print df.ix[:,'A']

>>>

a 0

b 4

c 8

Name: A, dtype: int32

以上這篇詳談Pandas中iloc和loc以及ix的區別就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

總結

以上是生活随笔為你收集整理的python中的ix是啥_详谈Pandas中iloc和loc以及ix的区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。