ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python pandas的八个生命周期总结

2022-10-26 12:41:56  阅读:344  来源: 互联网

标签:python Pandas 总结 生命周期


这里从八个pandas的数据处理生命周期,整理汇总出pandas框架在整个数据处理过程中都是如何处理数据的。

也就是从pandas的数据表对象以及数据汇总、数据统计等等直到数据导出的八个处理过程来完成pandas使用的汇总处理。

首先,需要准备好将python非标准库导入进来,除了pandas之外一般伴随数据分析处理使用的还有numpy科学计算库。

# Importing the pandas library and giving it the alias pd.
import pandas as pd

# Importing the numpy library and giving it the alias np.
import numpy as np

 

1、数据表对象(DataFrame)

在pandas的数据分析处理中,主要依赖的是对DataFrame对象的处理来完成数据的提取、汇总、统计等操作。

那么在初始化DataFrame对象的时候有两种方式,一种是直接读取Excel、csv文件获取数据后返回DataFrame数据对象。

# Reading the csv file and converting it into a dataframe.
dataframe_csv = pd.DataFrame(pd.read_csv('./data.csv'))

# Reading the excel file and converting it into a dataframe.
dataframe_xlsx = pd.DataFrame(pd.read_excel('./data.xlsx'))

另一种则是需要自己创建DataFrame对象的数据,将字典等类型的python对象直接初始化为DataFrame数据表的形式。

# Creating a dataframe with two columns, one called `name` and the other called `age`.
dataframe = pd.DataFrame({"编程语言": ['Java', 'Python', 'C++'],
                        "已诞生多少年": [23, 20, 28]},
                       columns=['编程语言', '已诞生多少年'])

 

2、数据表(DataFrame)结构信息

通过DataFrame对象内置的各种函数来查看数据维度、列名称、数据格式等信息。

# Creating a dataframe with two columns, one called `name` and the other called `age`.
dataframe = pd.DataFrame({"编程语言": ['Java', 'Python', 'C++'],
                        "已诞生多少年": [23, 20, 28]},
                       columns=['编程语言', '已诞生多少年'])

【加粗】dataframe.info()

查看数据表的基本信息展示,包括列数、数据格式、列名称、占用空间等。

dataframe.info()

# <class 'pandas.core.frame.DataFrame'>
# Index: 0 entries
# Data columns (total 2 columns):
#  #   Column  Non-Null Count  Dtype
# ---  ------  --------------  -----
#  0   编程语言    0 non-null      object
#  1   已诞生多少年  0 non-null      object
# dtypes: object(2)
# memory usage: 0.0+ bytes

【加粗】dataframe.columns

查看DataFrame对象的所有列的名称,并返回数组信息。

print('显示所有列的名称是:{0}'.format(dataframe.columns))

# 显示所有列的名称是:Index(['编程语言', '已诞生多少年'], dtype='object')

【加粗】dataframe['列名'].dtype

查看DataFrame对象中某一列的格式dtype是什么。

print('列名(编程语言)的格式是:{0}'.format(dataframe[u'编程语言'].dtype))

# 列名(编程语言)的格式是:object

【加粗】dataframe.shape

通过DataFrame对象的shape函数,进而展示出数据是几行几列的结构。

print('dataframe的结构是:{0}'.format(dataframe.shape))

# dataframe的结构是:(3, 2)

【加粗】dataframe.values

使用DataFrame对象的values函数,得出所有数据内容的结果。

# Importing the pprint function from the pprint module.
from pprint import pprint

pprint('dataframe对象的值是:{0}'.format(dataframe.values))

# "dataframe对象的值是:[['Java' 23]\n ['Python' 20]\n ['C++' 28]]"

 

3、数据清洗

数据清洗即是对DataFrame对象中的数据进行规范化的处理,比如空值的数据填充、重复数据的清理、数据格式的统一转换等等。

【加粗】dataframe.fillna()

# 将所有数据为空的项填充为0
dataframe.fillna(value=0)

# 使用均值进行填充
dataframe[u'已诞生多少年'].fillna(dataframe[u'已诞生多少年'].mean())

【加粗】map(str.strip)

# 去除指定列的首尾多余的空格后,再重新赋值给所在列

dataframe[u'编程语言'] = dataframe[u'编程语言'].map(str.strip)

【加粗】dataframe.astype

# 更改DataFrame数据对象中某个列的数据格式。

dataframe[u'已诞生多少年'].astype('int')

【加粗】dataframe.rename

# 更改DataFrame数据对象中某个列的名称

dataframe.rename(columns={u'已诞生多少年': u'语言年龄'})

【加粗】 dataframe.drop_duplicates

# 以DataFrame中的某个列为准,删除其中的重复项

dataframe[u'编程语言'].drop_duplicates()

【加粗】dataframe.replace

# 替换DataFrame数据对象中某个列中指定的值

dataframe[u'编程语言'].replace('Java', 'C#')

 

4、数据预梳理

数据预处理(data preprocessing)是指在主要的处理以前对数据进行的一些处理。

如对大部分地球物理面积性观测数据在进行转换或增强处理之前,首先将不规则分布的测网经过插值转换为规则网的处理,以利于计算机的运算。

【加粗】数据合并

使用DataFrame对象数据合并的有四种方式可以选择,分别是merge、append、join、concat方式,不同方式实现的效果是不同的。

接下来使用两种比较常见的方式append、concat、join来演示一下DataFrame对象合并的效果。

使用两个DataFrame的数据对象通过append将对象的数据内容进行合并。

# Creating a dataframe with two columns, one called `编程语言` and the other called `已诞生多少年`.
dataframeA = pd.DataFrame({"编程语言": ['Java', 'Python', 'C++'],
                         "已诞生多少年": [23, 20, 28]}, columns=['编程语言', '已诞生多少年'])

# Creating a dataframe with two columns, one called `编程语言` and the other called `已诞生多少年`.
dataframeB = pd.DataFrame({"编程语言": ['Scala', 'C#', 'Go'],
                         "已诞生多少年": [23, 20, 28]}, columns=['编程语言', '已诞生多少年'])

# Appending the dataframeB to the dataframeA.
res = dataframeA.append(dataframeB)

# Printing the result of the append operation.
print(res)

#      编程语言  已诞生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28
# 0   Scala      23
# 1      C#      20
# 2      Go      28
#
# Process finished with exit code 0

使用两个DataFrame的数据对象通过concat将对象的数据内容进行合并。

# Concatenating the two dataframes together.
res = pd.concat([dataframeA, dataframeB])

# Printing the result of the append operation.
print(res)

#      编程语言  已诞生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28
# 0   Scala      23
# 1      C#      20
# 2      Go      28

concat函数的合并效果和append函数有异曲同工之妙,两者同样都是对数据内容进行纵向合并的。

使用两个DataFrame的数据对象通过join将对象的数据结构及数据内容进行横向合并。

# Creating a dataframe with two columns, one called `编程语言` and the other called `已诞生多少年`.
dataframeC = pd.DataFrame({"编程语言": ['Java', 'Python', 'C++'],
                         "已诞生多少年": [23, 20, 28]}, columns=['编程语言', '已诞生多少年'])

# Creating a dataframe with one column called `历史表现` and three rows.
dataframeD = pd.DataFrame({"历史表现": ['A', 'A', 'A']})

# Joining the two dataframes together.
res = dataframeC.join(dataframeD, on=None)

# Printing the result of the append operation.
print(res)

#      编程语言  已诞生多少年 历史表现
# 0    Java      23    A
# 1  Python      20    A
# 2     C++      28    A

可以发现使用join的函数之后,将dataframeD作为一个列扩展了并且对应的每一行都准确的填充了数据A。

【加粗】设置索引

给DataFrame对象设置索引的话就比较方便了,直接DataFrame对象提供的set_index函数设置需要定义索引的列名称就OK了。

# Creating a dataframe with two columns, one called `编程语言` and the other called `已诞生多少年`.
dataframeE = pd.DataFrame({"编程语言": ['Java', 'Python', 'C++'],
                         "已诞生多少年": [23, 20, 28]}, columns=['编程语言', '已诞生多少年'])

# Setting the index of the dataframe to the column `编程语言`.
dataframeE.set_index(u'编程语言')

# Printing the dataframeE.
print(dataframeE)

#      编程语言  已诞生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28

【加粗】数据排序

DataFrame数据对象的排序主要是通过索引排序、某个指定列排序的方式为参照完成对DataFrame对象中的整个数据内容排序。

# Sorting the dataframeE by the index.
res = dataframeE.sort_index()

# Printing the res.
print(res)

#      编程语言  已诞生多少年
# 0    Java      23
# 1  Python      20
# 2     C++      28

# Sorting the dataframeE by the column `已诞生多少年`.
res = dataframeE.sort_values(by=['已诞生多少年'], ascending=False)

# Printing the res.
print(res)

#      编程语言  已诞生多少年
# 2     C++      28
# 0    Java      23
# 1  Python      20

sort_index函数是指按照当前DataFrame数据对象的索引进行排序,sort_values则是按照指定的一个或多个列的值进行降序或者升序。

【加粗】数据分组

数据预处理中的数据分组主要是需要的分组的数据打上特殊的标记以便于后期对数据的归类处理。

比较简单一些的分组处理可以使用numpy中提供的函数进行处理,这里使用numpy的where函数来设置过滤条件。

# Creating a new column called `分组标记(高龄/低龄)` and setting the value to `高` if the value in the column `已诞生多少年` is greater
# than or equal to 23, otherwise it is setting the value to `低`.
dataframeE['分组标记(高龄/低龄)'] = np.where(dataframeE[u'已诞生多少年'] >= 23, '高', '低')

# Printing the dataframeE.
print(dataframeE)

#      编程语言  已诞生多少年 分组标记(高龄/低龄)
# 0    Java      23           高
# 1  Python      20           低
# 2     C++      28           高

稍微复杂一些的过滤条件可以使用多条件的过滤方式找出符合要求的数据项进行分组标记。

# Creating a new column called `分组标记(高龄/低龄,是否是Java)` and setting the value to `高/是` if the value in the column `已诞生多少年` is
# greater than or equal to 23 and the value in the column `编程语言` is equal to `Java`, otherwise it is setting the value to
# `低/否`.
dataframeE['分组标记(高龄/低龄,是否是Java)'] = np.where((dataframeE[u'已诞生多少年'] >= 23) & (dataframeE[u'编程语言'] == 'Java'), '高/是',
                                           '低/否')

# Printing the dataframeE.
print(dataframeE)

#      编程语言  已诞生多少年 分组标记(高龄/低龄) 分组标记(高龄/低龄,是否是Java)
# 0    Java      23           高                 高/是
# 1  Python      20           低                 低/否
# 2     C++      28           高                 低/否

 

5、提取数据

数据提取即是对符合要求的数据完成提取操作,DataFrame对象提取数据主要是按照标签值、标签值和位置以及数据位置进行提取。

DataFrame对象按照位置或位置区域提取数据,这里所说的位置其实就是DataFrame对象的索引。

基本上所有的操作都能够使用DataFrame对象的loc函数、iloc函数这两个函数来实现操作。

提取索引为2的DataFrame对象对应的行数据。

标签:python,Pandas,总结,生命周期
来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有