本文主要是介绍pandas iloc()函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文链接:https://blog.csdn.net/w_weiying/article/details/81411257
loc函数:通过行索引 "Index" 中的具体值来取行数据(如取"Index"为"A"的行)
iloc函数:通过行号来取行数据(如取第二行的数据)
本文给出loc、iloc常见的五种用法,并附上详细代码。
1. 利用loc、iloc提取行数据
- import numpy as np
- import pandas as pd
- #创建一个Dataframe
- data=pd.DataFrame(np.arange(16).reshape(4,4),index=list('abcd'),columns=list('ABCD'))
-
- In[1]: data
- Out[1]:
- A B C D
- a 0 1 2 3
- b 4 5 6 7
- c 8 9 10 11
- d 12 13 14 15
-
- #取索引为'a'的行
- In[2]: data.loc['a']
- Out[2]:
- A 0
- B 1
- C 2
- D 3
-
- #取第一行数据,索引为'a'的行就是第一行,所以结果相同
- In[3]: data.iloc[0]
- Out[3]:
- A 0
- B 1
- C 2
- D 3
2. 利用loc、iloc提取列数据
- In[4]:data.loc[:,['A']] #取'A'列所有行,多取几列格式为 data.loc[:,['A','B']]
- Out[4]:
- A
- a 0
- b 4
- c 8
- d 12
-
- In[5]:data.iloc[:,[0]] #取第0列所有行,多取几列格式为 data.iloc[:,[0,1]]
- Out[5]:
- A
- a 0
- b 4
- c 8
- d 12
-
3.利用loc、iloc提取指定行、指定列数据
- In[6]:data.loc[['a','b'],['A','B']] #提取index为'a','b',列名为'A','B'中的数据
- Out[6]:
- A B
- a 0 1
- b 4 5
-
- In[7]:data.iloc[[0,1],[0,1]] #提取第0、1行,第0、1列中的数据
- Out[7]:
- A B
- a 0 1
- b 4 5
4.利用loc、iloc提取所有数据
- In[8]:data.loc[:,:] #取A,B,C,D列的所有行
- Out[8]:
- A B C D
- a 0 1 2 3
- b 4 5 6 7
- c 8 9 10 11
- d 12 13 14 15
-
- In[9]:data.iloc[:,:] #取第0,1,2,3列的所有行
- Out[9]:
- A B C D
- a 0 1 2 3
- b 4 5 6 7
- c 8 9 10 11
- d 12 13 14 15
5.利用loc函数,根据某个数据来提取数据所在的行
- In[10]: data.loc[data['A']==0] #提取data数据(筛选条件: A列中数字为0所在的行数据)
- Out[10]:
- A B C D
- a 0 1 2 3
-
- In[11]: data.loc[(data['A']==0)&(data['B']==2)] #提取data数据(多个筛选条件)
- Out[11]:
- A B C D
- a 0 1 2 3
同时,以下几种写法也可提取数据所在的行,与第五种用法类似,仅作补充。
- In[12]: data[data['A']==0] #dataframe用法
- In[13]: data[data['A'].isin([0])] #isin函数
- In[14]: data[(data['A']==0)&(data['B']==2)] #dataframe用法
- In[15]: data[(data['A'].isin([0]))&(data['B'].isin([2]))] #isin函数
-
- Out[15]:
- A B C D
- a 0 1 2 3
利用loc函数的时候,当index相同时,会将相同的Index全部提取出来,优点是:如果index是人名,数据框为所有人的数据,那么我可以将某个人的多条数据提取出来分析;缺点是:如果index不具有特定意义,而且重复,那么提取的数据需要进一步处理,可用.reset_index()函数重置index
同样:at与iat函数可抽取指定行列的值,详情见博文(DataFrame中at、iat函数详解)
最后:本博文中loc与iloc函数可提取指定行列数据,删除Dateframe指定行列数据可参考博主下列博文(点击跳转):
- Drop函数与isin函数(DataFrame删除指定行列)
- DataFrame提取(删除)指定行列(isin函数、drop函数)(高级用法详解,示例源码)
这篇关于pandas iloc()函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!