Home  >  Article  >  Backend Development  >  Examples to explain how Python uses pandas to query data

Examples to explain how Python uses pandas to query data

巴扎黑
巴扎黑Original
2017-09-02 10:47:071723browse

查询和分析数据是pandas的重要功能,也是我们学习pandas的基础,下面这篇文章主要给大家介绍了关于Python数据分析之如何利用pandas查询数据的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

在数据分析领域,最热门的莫过于Python和R语言,本文将详细给大家介绍关于Python利用pandas查询数据的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

示例代码

这里的查询数据相当于R语言里的subset功能,可以通过布尔索引有针对的选取原数据的子集、指定行、指定列等。我们先导入一个student数据集:


student = pd.io.parsers.read_csv('C:\\Users\\admin\\Desktop\\student.csv')

查询数据的前5行或末尾5行:


student.head()
student.tail()

查询指定的行:


student.ix[[0,2,4,5,7]] #这里的ix索引标签函数必须是中括号[]

查询指定的列:


student[['Name','Height','Weight']].head() #如果多个列的话,必须使用双重中括号

也可以通过ix索引标签查询指定的列:


student.ix[:,['Name','Height','Weight']].head()

查询指定的行和列:


student.ix[[0,2,4,5,7],['Name','Height','Weight']].head()

查询所有女生的信息:


student[student['Sex']=='F']

查询出所有12岁以上的女生信息:


student[(student['Sex']=='F') & (student['Age']>12)]

查询出所有12岁以上的女生姓名、身高和体重:


student[(student['Sex']=='F') & (student['Age']>12)][['Name','Height','Weight']]

上面的查询逻辑其实非常的简单,需要注意的是,如果是多个条件的查询,必须在&(且)或者|(或)的两端条件用括号括起来。

The above is the detailed content of Examples to explain how Python uses pandas to query data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn