发布于2022-11-17 21:14 阅读(747) 评论(0) 点赞(17) 收藏(5)
提示:该文章仅适合小白同学,如有错误的地方欢迎大佬在评论处赐教
1、Pandas是python的一个数据分析包,为解决数据分析任务而创建的;
2、Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具;
3、pandas提供了大量能使我们快速便捷地处理数据的函数和方法;它是使Python成为强大而高效的数据分析环境的重要因素之一;
示例数据(csv,xlsx)地址自行提取-提取码:3uqa:https://pan.baidu.com/s/1Tz-NiSgpCyzOOW5LvPKHEA?pwd=3uqa
提示:以下是本篇文章正文内容,下面案例可供参考
镜像地址
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/
安装最新版本:pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
我的pandas版本:1.1.3;
指定版本安装:pip install pandas==1.1.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
read_excel() 参数介绍:
io:文件地址
sheet_name:工资表中的子表名,默认为:sheet1
index_col: 指定行索引, 默认None, 可以是数字/list
usecols:usecols=[‘user’,“pwd”] 指定user,pwd列进行读取、默认(usecols=None)全部读取
skiprows:根据数字索引跳过行数据,默认从第0行开始
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
print(sheet1.head(5)) # 控制台打印前5条数据
read_csv()参数介绍:
filepath_or_buffer:文件地址
sep:以什么分隔,sep=“\t"以tab键分隔,默认以英文逗号(”,")分隔
index_col: 指定行索引, 默认None, 可以是数字/list
usecols:usecols=[‘user’,“pwd”] 指定user,pwd列进行读取、默认(usecols=None)全部读取
skiprows:根据数字索引跳过行数据,默认从第0行开始
import pandas as pd
sheet1 = pd.read_csv(filepath_or_buffer='非洲通讯产品销售数据.csv', sep=',', skiprows=0, usecols=None)
print(sheet1.head(5)) # 控制台打印前5条数据
import pandas as pd
sheet1 = pd.read_csv(filepath_or_buffer='long-customer-train.csv', sep=',', skiprows=0, usecols=None)
duplicated_num = sheet1.duplicated(subset=['user_id']).sum() # 统计user_id列 重复值的数量
print("user_id重复列数:", duplicated_num)
sheet1.drop_duplicates('user_id', inplace=True)
duplicated_num = sheet1.duplicated(subset=['user_id']).sum() # 再次统计user_id列 重复值的数量
print("剔除后-user_id重复列数:", duplicated_num)
dropna()参数介绍:
axis:0(对行数据进行剔除)、1(对列数据进行剔除),默认为0
how:any(行中有任意一个空值则剔除), all(行中全部为空值则剔除)
inplace:是否在该对象进行修改
import pandas as pd
sheet1 = pd.read_csv(filepath_or_buffer='long-customer-train.csv', sep=',', skiprows=0, usecols=None)
all_null = sheet1.isnull().sum(axis=0).sum() # 统计所有的缺失值行数
print("缺失值行数:", all_null)
sheet1.dropna(axis=0, how='any', inplace=True) # 剔除每行任一个为空值的数据
all_null = sheet1.isnull().sum(axis=0).sum() # 统计所有的缺失值行数
print("剔除后的缺失值行数:", all_null)
需求:“Age”列存在数值为-1、0 和“-”的异常值,删除存在该情况的行数据;“Age”列存在空格和“岁”等异常字符,删除这些异常字符但须保留年龄数值
import pandas as pd sheet1 = pd.read_csv(filepath_or_buffer='long-customer-train.csv', sep=',', skiprows=0, usecols=None) print("异常值处理前:") print(sheet1['Age'].head(5)) for index, row in sheet1.iterrows(): if '-' in row['Age'] or len(row['Age'].strip()) < 1: # 异常值特征定义 sheet1.drop(index=index, inplace=True) # 根据索引就行剔除 elif '岁' in row['Age']: row['Age'] = row['Age'].replace('岁', '').strip() # 需要修改的字段定义 sheet1.loc[index] = row # 根据索引对该行数据进行修改 elif float(row['Age']) <= 0: sheet1.drop(index=index, inplace=True) print("异常值处理后:") print(sheet1['Age'].head(5))
import pandas as pd
sheet1 = pd.read_csv(filepath_or_buffer='long-customer-train.csv', sep=',', skiprows=0, usecols=None)
print(sheet1.head(5))
sheet1.drop(index=0, inplace=True) # 根据索引,行剔除
sheet1.drop(labels=['城市', '地区'], axis=1, inplace=True) # 按列 删除(城市, 地区)列
print(sheet1.head(5))
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
area_list = sheet1['地区'].values.tolist() # 提取地区列,转为list
sheet1_data_list = sheet1.values.tolist()
print("地区列:", area_list[:5]) # 一维列表
print("全部列:", sheet1_data_list[:5]) # 二维列表
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
sheet1 = sheet1.loc[0:4, ['日期', '国家']] # 提取前5行, 日期、国家列
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
sheet1 = sheet1.iloc[0:4, 1:3] # 提取前5行, 1、2、3 列
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
print(sheet1.head(5))
# 根据条件 指定"利润"字段赋值, 条件符号:或(|),与(&)
sheet1.loc[(sheet1['销售额'] <= 600) & (sheet1['利润'] <= 20), '利润'] = 8888
print(sheet1.head(5))
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
# print(sheet1.head(5)) # 打印前5条数据
# print(sheet1.tail(5)) # 打印最后5条数据
# print(sheet1.shape) # 打印行数和列数
# print(sheet1.columns.tolist()) # 提取列名转为list
# sheet1['国家'] = sheet1['国家'].astype(str) # 修改字段类型
# sheet1.columns = ['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7'] # 设置列名
# sheet1.rename(columns={'国家': '国家-test'}, inplace=True) # 修改列名
# sheet1.fillna(value=0, inplace=True) # 填充空值, value=填充的值
# sheet1['年度'] = sheet1['日期'].dt.year # 根据日期字段 新增年份列
# sheet1['季度'] = sheet1['日期'].dt.quarter # 根据日期字段 新增季度列
# sheet1.reset_index() # 重置索引
# sheet1.concat(obj1, obj2) # 将两个DataFrame对象进行合并
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
# print(sheet1['利润'].sum()) # 该列求和
# print(sheet1['利润'].max()) # 该列最大值
# print(sheet1['利润'].min()) # 该列最小值
# print(sheet1['利润'].mean()) # 该列平均值
# print(sheet1['利润'].mean(axis=1)) # 每行 平均值
# print(sheet1['利润'].median()) # 该列中位数
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
sheet1['年度'] = sheet1['日期'].dt.year # 根据日期字段 新增年份列
sheet1['季度'] = sheet1['日期'].dt.quarter # 根据日期字段 新增季度列
# 按年度分组,指定销售额列进行求和计算
compute_result = sheet1.groupby("年度")['销售额'].sum()
print(compute_result)
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
sheet1['年度'] = sheet1['日期'].dt.year # 根据日期字段 新增年份列
sheet1['季度'] = sheet1['日期'].dt.quarter # 根据日期字段 新增季度列
# 针对字段:年度、国家进行分组,求和计算字段:销售额、利润
compute_result = sheet1.groupby(['年度', '地区']).agg({"销售额": 'sum', "利润": "sum"})
print(compute_result)
# agg 聚合, 可用列表和字典作为参数, 常用函数:mean/sum/median/min/max/last/first
# 分组后对某列进行多个函数计算
# compute_result = sheet1.groupby(['年度', '地区']).agg({"销售额": ['sum', 'min'], "利润": [np.mean, max]})
def data_parse(rows):
return '1111'
# map() 将该列的元素迭代传入data_parse()函数作为参数,可以在函数内对该数据进行处理,return一个新值
sheet1['国家'] = sheet1['国家'].map(data_parse)
print(sheet1.head(5))
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
sheet1 = sheet1.loc[0:4, ['日期', '国家']] # # 提取前5行, 日期、国家列
sheet1.to_excel(excel_writer='test.xlsx')
import pandas as pd
sheet1 = pd.read_excel(io='非洲通讯产品销售数据.xlsx', sheet_name='SalesData', skiprows=0, usecols=None)
sheet1 = sheet1.loc[0:4, ['日期', '国家']] # # 提取前5行, 日期、国家列
sheet1.to_csv(path_or_buf='test.csv')
以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法,续有常用的pandas函数会在这篇博客中持续更新。
原文链接:https://blog.csdn.net/EXIxiaozhou/article/details/127854176
作者:dfh8374
链接:https://www.pythonheidong.com/blog/article/1858023/03899032bad7f75dd30f/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!