Python Pandas 模块教程

Python Pandas 模块

*Pandas数据库是 Python 中的开源库,它提供了可用的高性能数据结构和数据分析工具 *Pandas数据模块运行在 NumPy的顶部,并且通常用于数据科学和数据分析 *NumPy是一个支持多维数组和广泛的数学数组操作的低级数据结构。Pandas有一个更高级别的界面。它还提供了表数据的简化对齐和强大的时间序列功能 *DataFrame是 Pandas 中的关键数据结构。它允许我们将表数据存储和操纵为 2D 数据结构 *Pandas提供了数据框


安装和与 Pandas 开始

您需要有 Python 2.7 及以上版本才能安装 Pandas 模块. 如果您正在使用 conda,则可以使用下面的命令安装它。

1conda install pandas

如果您使用的是 PIP,然后运行下面的命令来安装 pandas 模块。

1pip3.7 install pandas

Python Install Pandas Module

要在 Python 脚本中导入 Pandas 和 NumPy,请添加下面的代码:

1import pandas as pd
2import numpy as np

由于Pandas依赖NumPy库,我们需要导入这种依赖。


Pandas模块中的数据结构

Pandas模块提供的3个数据结构如下:

  • 系列:它是一个具有均匀数据的 1-D 尺寸不变的结构数组
  • DataFrames:它是一个 2D 尺寸可变的表结构,具有异常键入的列
  • 面板:它是一个 3D 尺寸可变的数组

潘基文数据框

DataFrame 是最重要的和广泛使用的数据结构,是存储数据的标准方式. DataFrame 有数据在行和列中排列,如 SQL 表或表格数据库. 我们可以将数据硬编码到 DataFrame 或导入 CSV 文件, tsv 文件, Excel 文件, SQL 表等我们可以使用下面的构建器创建 DataFrame 对象。

1pandas.DataFrame(data, index, columns, dtype, copy)

以下是参数的简要描述:

它可以是列表,Dict,系列,Numpy ndarrays甚至,任何其他DataFrame

  • index - 有行标签
  • columns - 用于创建列标签
  • dtype - 用于指定每个列的数据类型,可选参数
  • 复制 - 用于复制数据,如果有

创建DataFrame的方法有很多,我们可以从DataFrame(社区/教程/python字典)或字典列表中创建DataFrame对象,我们也可以从Tuples列表、CSV、Excel文件等创建DataFrame。

1import pandas as pd
2import numpy as np
3df = pd.DataFrame({
4    "State": ['Andhra Pradesh', 'Maharashtra', 'Karnataka', 'Kerala', 'Tamil Nadu'],
5    "Capital": ['Hyderabad', 'Mumbai', 'Bengaluru', 'Trivandrum', 'Chennai'],
6    "Literacy %": [89, 77, 82, 97,85],
7    "Avg High Temp(c)": [33, 30, 29, 31, 32 ]
8})
9print(df)

Output: Python pandas Dataframe The first step is to create a dictionary. The second step is to pass the dictionary as an argument in the DataFrame() method. The final step is to print the DataFrame. As you see, the DataFrame can be compared to a table having heterogeneous value. Also, the size of the DataFrame can be modified. We have supplied the data in the form of the map and the keys of the map are considered by Pandas as the row labels. The index is displayed in the leftmost column and has the row labels. The column header and data are displayed in a tabular fashion. It is also possible to create indexed DataFrames. This can be done by configuring the index parameter in the DataFrame() method.


将 CSV 数据导入 DataFrame

我们还可以通过导入 CSV 文件来创建 DataFrame. CSV 文件是一个文本文件,每个行都有一个数据记录。记录中的值是使用comma字符分开的。 Pandas 提供了一个有用的方法,名为read_csv()来读取 CSV 文件的内容到 DataFrame。例如,我们可以创建一个名为cities.csv的文件,其中包含印度城市的详细信息。 CSV 文件存储在包含 Python 脚本的相同目录中。

1import pandas as pd
2data =  pd.read_csv('cities.csv')
3print(data)

我们的目标是加载数据并分析它以得出结论,因此,我们可以使用任何方便的方法来加载数据。


在 DataFrame 中查看数据

使用其名称运行DataFrame会显示整个表格。实时分析的数据集将有数以千计的行。为了分析数据,我们需要从大量数据集中检查数据。Panda提供许多有用的功能来检查我们只需要的数据。我们可以使用df.head(n)来获取第一个n行或df.tail(n)来打印最后一个n行。例如,下面的代码打印了DataFrame的第一个2行和最后一个行。

1print(df.head(2))

Output: Head

1print(df.tail(1))

Output: Tail Similarly, print(df.dtypes) prints the data types. Output: Dtype print(df.index) prints index. Output: print(df.columns) prints the columns of the DataFrame. Output: Columns print(df.values) displays the table values. Output: Values


1、统计记录的摘要

我们可以使用 df.describe() 函数获取数据的统计概要(计数、平均值、标准偏差、min、max 等)。

1print(df['Literacy %'].describe())

Output: Describe The df.describe() function displays the statistical summary, along with the data type.


二、记录分类

我们可以使用 df.sort_values() 函数对任何列进行排序。

1print(df.sort_values('Literacy %', ascending=False))

Output: Sort


3、剪辑记录

通过使用列名提取特定列的数据是可能的,例如,为了提取资本列,我们使用:

1df['Capital']

1(df.Capital)

Output: Slice Capitals It is also possible to slice multiple columns. This is done by enclosing multiple column names enclosed in 2 square brackets, with the column names separated using commas. The following code slices the 'State' and 'Capital' columns of the DataFrame.

1print(df[['State', 'Capital']])

Output: Slicemultiplecol It is also possible to slice rows. Multiple rows can be selected using ":" operator. The below code returns the first 3 rows.

1df[0:3]

Output: Slicerows An interesting feature of Pandas library is to select data based on its row and column labels using iloc[0] function. Many times, we may need only few columns to analyze. We can also can select by index using loc['index_one']). For example, to select the second row, we can use df.iloc[1,:] . Let's say, we need to select second element of the second column. This can be done by using df.iloc[1,1] function. In this example, the function df.iloc[1,1] displays "Mumbai" as output.


4、过滤数据

还可以过滤列值,例如,下面的代码过滤具有 90% 以上文盲率% 的列。

1print(df[df['Literacy %']>90])

Any comparison operator can be used to filter, based on a condition. Output: Filter Lit Another way to filter data is using the isin. Following is the code to filter only 2 states 'Karnataka' and 'Tamil Nadu'.

1print(df[df['State'].isin(['Karnataka', 'Tamil Nadu'])])

Output: Filter


五、重命名列表

可以使用 df.rename() 函数来重命名列. 该函数将旧列名和新列名作为参数。

1df.rename(columns = {'Literacy %':'Literacy percentage'}, inplace=True)
2print(df.head())

The argument inplace=True makes the changes to the DataFrame. Output: Rename


6、数据转移

Data Science 涉及数据的处理,以便数据能够与数据算法一起工作。 Data Wrangling 是数据的处理过程,如合并、组合和连接。 Pandas 库提供有用的函数,如 merge()groupby()concat() 来支持 Data Wrangling 任务。

1import pandas as pd
2
3d = {  
4    'Employee_id': ['1', '2', '3', '4', '5'],
5    'Employee_name': ['Akshar', 'Jones', 'Kate', 'Mike', 'Tina']
6}
7df1 = pd.DataFrame(d, columns=['Employee_id', 'Employee_name'])  
8print(df1)

Output: Wrangling 1 Let's create the second DataFrame using the below code:

1import pandas as pd
2
3data = {  
4    'Employee_id': ['4', '5', '6', '7', '8'],
5    'Employee_name': ['Meera', 'Tia', 'Varsha', 'Williams', 'Ziva']
6}
7df2 = pd.DataFrame(data, columns=['Employee_id', 'Employee_name'])  
8print(df2)

Output: Wrangling 2


A.合并

现在,让我们将我们创建的2个数据框合并到使用合并()函数的Employee_id值:

1print(pd.merge(df1, df2, on='Employee_id'))

Output: Merging We can see that merge() function returns the rows from both the DataFrames having the same column value, that was used while merging.


B、团体

组合是将数据收集到不同的类别的过程,例如,在下面的示例中,Employee_Name字段有Meera的名称两次,因此,让我们将其按Employee_name列组合。

 1import pandas as pd
 2import numpy as np
 3
 4data = {
 5    'Employee_id': ['4', '5', '6', '7', '8'],
 6    'Employee_name': ['Meera', 'Meera', 'Varsha', 'Williams', 'Ziva']
 7}
 8df2 = pd.DataFrame(data)
 9
10group = df2.groupby('Employee_name')
11print(group.get_group('Meera'))

The 'Employee_name' field having value 'Meera' is grouped by the column "Employee_name". The sample output is as below: Output: Grouping


C、合并

将数据连接包括将一组数据添加到另一组数据中。Pandas提供一个名为concat()的函数来连接DataFrames. 例如,让我们连接DataFrames的df1df2,使用:

1print(pd.concat([df1, df2]))

Output: Concatenation


通过 Dict of Series 创建数据框

要创建一个系列,我们可以使用 pd.Series() 方法并将一个数组传递给它。

1series_sample = pd.Series([100, 200, 300, 400])
2print(series_sample)

Output: Series Sample We have created a Series. You can see that 2 columns are displayed. The first column contains the index values starting from 0. The second column contains the elements passed as series. It is possible to create a DataFrame by passing a dictionary of Series. Let's create a DataFrame that is formed by uniting and passing the indexes of the series. Example

1d = {'Matches played' : pd.Series([400, 300, 200], index=['Sachin', 'Kohli', 'Raina']),
2'Position' : pd.Series([1, 2, 3, 4], index=['Sachin', 'Kohli', 'Raina', 'Dravid'])}
3df = pd.DataFrame(d)
4print(df)

Sample output Df Dictseries For series one, as we have not specified label 'd', NaN is returned.


列选择、添加、删除

可以从DataFrame中选择一个特定的列,例如,要只显示第一列,我们可以重写上面的代码:

1d = {'Matches played' : pd.Series([400, 300, 200], index=['Sachin', 'Kohli', 'Raina']),
2 'Position' : pd.Series([1, 2, 3, 4], index=['Sachin', 'Kohli', 'Raina', 'Dravid'])}
3df = pd.DataFrame(d)
4print(df['Matches played'])

The above code prints only the "Matches played" column of the DataFrame. Output Col Selection It is also possible to add columns to an existing DataFrame. For example, the below code adds a new column named "Runrate" to the above DataFrame.

1d = {'Matches played' : pd.Series([400, 300, 200], index=['Sachin', 'Kohli', 'Raina']),
2 'Position' : pd.Series([1, 2, 3, 4], index=['Sachin', 'Kohli', 'Raina', 'Dravid'])}
3df = pd.DataFrame(d)
4df['Runrate']=pd.Series([80, 70, 60, 50], index=['Sachin', 'Kohli', 'Raina', 'Dravid'])
5print(df)

Output: Col Addition We can delete columns using the delete and pop functions. For example to delete the 'Matches played' column in the above example, we can do it by either of the below 2 ways:

1del df['Matches played']

1df.pop('Matches played')

Output: Delcolum


结论

在本教程中,我们对Python Pandas图书馆进行了简短的介绍,我们还做了一些实用的例子,以释放用于数据科学领域的Pandas图书馆的力量。

Published At
Categories with 技术
Tagged with
comments powered by Disqus