在使用pandas时,loc和iloc让我踩了几次坑。所以在此记录一下二者的区别。
In [1]: import pandas as pdIn [2]: import numpy as npIn [3]: d = pd.DataFrame(np.arange(20).reshape(5, 4), columns=List('abcd'))In [4]: dOut[4]: a b c d0 0 1 2 31 4 5 6 72 8 9 10 113 12 13 14 154 16 17 18 19In [5]:
1、在取某一列的时候,loc的列参数是列名,而iloc的列参数是该列的索引。例如取b列:
In [5]: d.loc[:, 'b']Out[5]: 0 11 52 93 134 17name: b, dtype: int64In [6]: d.iloc[:, 1]Out[6]: 0 11 52 93 134 17name: b, dtype: int64
2、在取某一行的时候,loc的行参数是索引值, 而iloc的行参数是“行号”,第一行的行号就是0,第二行的行号就是1。我们把d倒序一下,然后取第一行就会发现区别:
In [7]: e = d.sort_index(ascending=False)In [8]: eOut[8]: a b c d4 16 17 18 193 12 13 14 152 8 9 10 111 4 5 6 70 0 1 2 3In [9]: e.loc[0, :]Out[9]: a 0b 1c 2d 3name: 0, dtype: int64In [10]: e.iloc[0, :]Out[10]: a 16b 17c 18d 19name: 4, dtype: int64
可以看到iloc并没有按照索引取行,而是取了第一行。
以上是loc和iloc的两点区别,欢迎补充!
总结以上是内存溢出为你收集整理的Python DataFrame 中loc和iloc的区别全部内容,希望文章能够帮你解决Python DataFrame 中loc和iloc的区别所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)