python中的ix是啥_详谈Pandas中iloc和loc以及ix的区别
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 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是一種混合索引,字符型標簽和整型數(shù)據(jù)索引都可以。
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的區(qū)別就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
總結(jié)
以上是生活随笔為你收集整理的python中的ix是啥_详谈Pandas中iloc和loc以及ix的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米12 Pro升级版曝光:处理器换成天
- 下一篇: 关机时无人照管更新正在运行_了解iOS1