国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳談Pandas中iloc和loc以及ix的區(qū)別

2020-02-15 21:41:31
字體:
供稿:網(wǎng)友

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

1. iloc和loc的區(qū)別:

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

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

import pandas as pdimport numpy as npa = 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 30 0 1 2 31 4 5 6 72 8 9 10 11print df.loc[0]>>>0 01 12 23 3Name: 0, dtype: int32print df.iloc[0]0 01 12 23 3Name: 0, dtype: int32print df.loc[:,[0,3]] 0 30 0 31 4 72 8 11print df.iloc[:,[0,3]] 0 30 0 31 4 72 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 <class 'pandas.core.indexes.base.Index'> with these indexers [0] of <type 'int'> 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 <class 'pandas.core.indexes.base.Index'> with these indexers [a] of <type 'str'> 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 Da 0 1 2 3b 4 5 6 7c 8 9 10 11print df.loc[:,'A']>>>a 0b 4c 8Name: A, dtype: int32print 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是一種混合索引,字符型標簽和整型數(shù)據(jù)索引都可以。

print df.ix[0]>>>A 0B 1C 2D 3Name: a, dtype: int32print df.ix['a']>>>A 0B 1C 2D 3Name: a, dtype: int32print df.ix[:,0]>>>a 0b 4c 8Name: A, dtype: int32print df.ix[:,'A']>>>a 0b 4c 8Name: A, dtype: int32

以上這篇詳談Pandas中iloc和loc以及ix的區(qū)別就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 河北区| 延边| 平遥县| 阳高县| 光山县| 女性| 澜沧| 福安市| 雷州市| 钟祥市| 安顺市| 霍林郭勒市| 南丰县| 昂仁县| 新蔡县| 万安县| 淮北市| 澄城县| 确山县| 彭泽县| 德江县| 务川| 苗栗市| 罗田县| 昌都县| 根河市| 介休市| 扎鲁特旗| 汝南县| 平陆县| 蓬安县| 正阳县| 迁西县| 玉树县| 林芝县| 贵德县| 林口县| 鄂州市| 嘉义县| 上蔡县| 玉田县|