说是定长是因为在存储的时候,相当于两个 ndarray,这也是和字典结构最大的不同。因为在字典的结构里,元素的个数是不固定的。 Series 有两个基本属性:index 和 values。在 Series 结构中,index 默认是 0,1,2,……递增的整数序列,当然我们也可以自己来指定索引,比如 index=['a’, 'b’, 'c’, 'd’]。
!pip3 install pandas -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
# 创建series import pandas as pd from pandas import Series, DataFrame ## index 采用的是默认值 x1 = Series([1,2,3,4]) ## index 进行了指定 x2 = Series(data=[1,2,3,4], index=['a', 'b', 'c', 'd']) print(x1) print(x2) # 采用字典的方式来创建 Series d = {'a':1, 'b':2, 'c':3, 'd':4} x3 = Series(d) print (x3)
0 1 1 2 2 3 3 4 dtype: int64 a 1 b 2 c 3 d 4 dtype: int64 a 1 b 2 c 3 d 4 dtype: int64
它包括了行索引和列索引,我们可以将 DataFrame 看成是由相同索引的 Series 组成的字典类型。
import pandas as pd from pandas import Series, DataFrame data = {'Chinese': [66, 95, 93, 90,80],'English': [65, 85, 92, 88, 90],'Math': [30, 98, 96, 77, 90]} ## 相当于把每个列基于同样地index序列化,index有点类似于主键??应该也可以取不唯一 df1= DataFrame(data) df2 = DataFrame(data, index=['ZhangFei', 'GuanYu', 'ZhaoYun', 'HuangZhong', 'DianWei'], columns=['English', 'Math', 'Chinese']) print(df1) print(df2)
Chinese English Math 0 66 65 30 1 95 85 98 2 93 92 96 3 90 88 77 4 80 90 90 English Math Chinese ZhangFei 65 30 66 GuanYu 85 98 95 ZhaoYun 92 96 93 HuangZhong 88 77 90 DianWei 90 90 80
Pandas 允许直接从 xlsx,csv 等文件中导入数据,也可以输出到 xlsx, csv 等文件,非常方便。
import pandas as pd from pandas import Series, DataFrame score = DataFrame(pd.read_excel('data.xlsx')) score.to_excel('data1.xlsx') print(score)
# 报错 XLRDError: Excel xlsx file; not supported
参考https://blog.csdn.net/weixin_44073728/article/details/111054157
pandas无法打开.xlsx文件,xlrd.biffh.XLRDError: Excel xlsx file; not supported
原因是最近xlrd更新到了2.0.1版本,只支持.xls文件。所以pandas.read_excel('xxx.xlsx’)会报错。
可以安装旧版xlrd,在cmd中运行:
pip uninstall xlrd
pip install xlrd==1.2.0 ##此方法解决不了
也可以用openpyxl代替xlrd打开.xlsx文件:
df=pandas.read_excel('data.xlsx’,engine='openpyxl’) ##可行
编辑data.xlsx上传
import pandas as pd
from pandas import Series, DataFrame
score = pd.read_excel('data.xlsx',engine='openpyxl')
score.to_excel('data1.xlsx')
print(score)
66 65 30
0 95 85 98
1 93 92 96
2 90 88 77
3 80 90 90
发现会把Excel的首行首列读成行列index,重新编辑上传,执行结果:
原来只会识别列名,每行如果不指定index还是会默认生成
Unnamed: 0 English Math Chinese
0 ZhangFei 66 65 30
1 GuanYu 95 85 98
2 ZhaoYun 93 92 96
3 HuangZhong 90 88 77
4 DianWei 80 90 90
数据清洗是数据准备过程中必不可少的环节,Pandas 也为我们提供了数据清洗的工具,在后面数据清洗的章节中会给你做详细的介绍,这里简单介绍下 Pandas 在数据清洗中的使用方法。
import numpy as np data = {'Chinese': [66, 95, 93, 90,80],'English': [65, 85, 92, 88, 90],'Math': [30, 98, 96, 77, 90]} df = DataFrame(data, index=['ZhangFei', 'GuanYu', 'ZhaoYun', 'HuangZhong', 'DianWei'], columns=['English', 'Math', 'Chinese']) ## 1. drop()删除 DataFrame 中的不必要的列或行 df1 = df.drop(columns=['Chinese']) df2 = df.drop(index=['ZhangFei']) print(df2) ## 2.rename(columns=new_names, inplace=True)重命名列名 columns,让列表名更容易识别 df2.rename(columns={'Chinese': 'YuWen', 'English': 'Yingyu'}, inplace = True) ## 3.drop_duplicates()去重复的行 df3=df.drop_duplicates() print(df1) print(df2) print(df3) ## 4.astype更改数据格式 df2['YuWen'].astype('str') ##df2['YuWen'].astype(np.int64) print(df2) ## 5.strip删除数据间的空格/指定字符 # df2['YuWen']=df2['YuWen'].map(str.strip) # df2['YuWen']=df2['YuWen'].map(str.lstrip) # df2['YuWen']=df2['YuWen'].map(str.rstrip) # df2['YuWen']=df2['YuWen'].str.strip('$') ## 6.大小写转换 df2.columns = df2.columns.str.upper() df2.columns = df2.columns.str.lower() df2.columns = df2.columns.str.title() ## 7.isnull()查找空值 ## 查看哪个地方存在空值 NaN,可以针对数据表 df 进行 df.isnull() ## 想知道哪列存在空值,可以使用 df.isnull().any() ## 8.apply 函数对数据进行清洗 ## 大小写转换df['name'] = df['name'].apply(str.upper) ## apply函数应用 def double_df(x): return 2*x df1['English'] = df1['English'].apply(double_df) ## apply复杂函数应用 def plus(df,n,m): df['new1'] = (df['English'] df['Math']) * m df['new2'] = (df['English'] df['Math']) * n return df print(df1.apply(plus,axis=1,args=(2,3,))) # 注意这里axis=0运行不了的 # 其中 axis=1 代表按照列为轴进行操作,axis=0 代表按照行为轴进行操作,args 是传递的两个参数,即 n=2, m=3,在 plus 函数中使用到了 n 和 m,从而生成新的 df。
English Math Chinese GuanYu 85 98 95 ZhaoYun 92 96 93 HuangZhong 88 77 90 DianWei 90 90 80 English Math ZhangFei 65 30 GuanYu 85 98 ZhaoYun 92 96 HuangZhong 88 77 DianWei 90 90 Yingyu Math YuWen GuanYu 85 98 95 ZhaoYun 92 96 93 HuangZhong 88 77 90 DianWei 90 90 80 English Math Chinese ZhangFei 65 30 66 GuanYu 85 98 95 ZhaoYun 92 96 93 HuangZhong 88 77 90 DianWei 90 90 80 Yingyu Math YuWen GuanYu 85 98 95 ZhaoYun 92 96 93 HuangZhong 88 77 90 DianWei 90 90 80 English Math new1 new2 ZhangFei 130 30 480 320 GuanYu 170 98 804 536 ZhaoYun 184 96 840 560 HuangZhong 176 77 759 506 DianWei 180 90 810 540
在数据清洗后,我们就要对数据进行统计了。Pandas 和 NumPy 一样,都有常用的统计函数,如果遇到空值 NaN,会自动排除。
# 统计函数千千万,describe() 函数最简便。它是个统计大礼包,可以快速让我们对数据有个全面的了解。 df1 = DataFrame({'name':['ZhangFei', 'GuanYu', 'a', 'b', 'c'], 'data1':range(5)}) print(df1) print(df1.describe())
name data1 0 ZhangFei 0 1 GuanYu 1 2 a 2 3 b 3 4 c 4 data1 count 5.000000 mean 2.000000 std 1.581139 min 0.000000 25% 1.000000 50% 2.000000 75% 3.000000 max 4.000000
有时候我们需要将多个渠道源的多个数据表进行合并,一个 DataFrame 相当于一个数据库的数据表,那么多个 DataFrame 数据表的合并就相当于多个数据库的表合并
# 创建两个dataframe df1 = DataFrame({'name':['ZhangFei', 'GuanYu', 'a', 'b', 'c'], 'data1':range(5)}) df2 = DataFrame({'name':['ZhangFei', 'GuanYu', 'A', 'B', 'C'], 'data2':range(5)}) ## 1.基于指定列连接 df3 = pd.merge(df1, df2, on='name') print(df3) ## 2.内连接:inner 内链接是 merge 合并的默认情况,inner 内连接其实也就是键的交集,在这里 df1, df2 相同的键是 name,所以是基于 name 字段做的连接 df3 = pd.merge(df1, df2, how='inner') print(df3) ## 3.左连接 df3 = pd.merge(df1, df2, how='left') print(df3) ## 4.右连接 df3 = pd.merge(df1, df2, how='right') print(df3) ## 5.外连接 df3 = pd.merge(df1, df2, how='outer') print(df3)
name data1 data2 0 ZhangFei 0 0 1 GuanYu 1 1 name data1 data2 0 ZhangFei 0 0 1 GuanYu 1 1 name data1 data2 0 ZhangFei 0 0.0 1 GuanYu 1 1.0 2 a 2 NaN 3 b 3 NaN 4 c 4 NaN name data1 data2 0 ZhangFei 0.0 0 1 GuanYu 1.0 1 2 A NaN 2 3 B NaN 3 4 C NaN 4 name data1 data2 0 ZhangFei 0.0 0.0 1 GuanYu 1.0 1.0 2 a 2.0 NaN 3 b 3.0 NaN 4 c 4.0 NaN 5 A NaN 2.0 6 B NaN 3.0 7 C NaN 4.0
工具:pandasql。 pandasql 中的主要函数是 sqldf,它接收两个参数:一个 SQL 查询语句,还有一组环境变量 globals() 或 locals()。这样我们就可以在 Python 里,直接用 SQL 语句中对 DataFrame 进行操作,举个例子:
!pip3 install pandasql -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
import pandas as pd from pandas import DataFrame from pandasql import sqldf, load_meat, load_births df1 = DataFrame({'name':['ZhangFei', 'GuanYu', 'a', 'b', 'c'], 'data1':range(5)}) pysqldf = lambda sql: sqldf(sql, globals()) sql = 'select * from df1 where name ='ZhangFei'' print(pysqldf(sql))
name data1
0 ZhangFei 0
lambda argument_list: expression
lambda 实际上是用来定义一个匿名函数的,argument_list 是参数列表,expression 是关于参数的表达式,会根据 expression 表达式计算结果进行输出返回。
对于下表的数据,请使用 Pandas 中的 DataFrame 进行创建,并对数据进行清洗。同时新增一列“总和”计算每个人的三科成绩之和
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pandas as pd data = {'Chinese': [66, 95, 93, 90, 80, 80], 'English': [65, 85, 92, 88, 90, 90], 'Math': [None, 98, 96, 77, 90, 90]} df = pd.DataFrame(data, index=['张飞', '关羽', '赵云', '黄忠', '典韦', '典韦'], columns=['English', 'Math', 'Chinese']) # 去除重复行 df = df.drop_duplicates() # 列名重新排序 cols = ['Chinese', 'English', 'Math'] df = df.filter(cols, axis=1) # 列名改为中文 df.rename(columns={'Chinese': '语文', 'English': '英语', 'Math': '数学'}, inplace=True) def total_score(df): df['总分'] = df['语文'] df['英语'] df['数学'] return df # 求成绩的和,用老师讲的 apply 方法,也可以用df['Total'] = df.sum(axis=1) df = df.apply(total_score, axis=1) # 或者可以用这个方法求和 # df['总分'] = df['语文'] df['英语'] df['数学'] # 按照总分排序,从高到低,此时有缺失值 df.sort_values(['总分'], ascending=[False], inplace=True) # 打印显示成绩单信息,张飞有空值 print(df.isnull().sum()) print(df.describe()) print(df) # 使用数学成绩均值填充张飞同学的缺失值 df['数学'].fillna(df['数学'].mean(), inplace=True) # 再次求成绩的和并打印显示成绩单情况 df = df.apply(total_score, axis=1) print(df.isnull().sum()) print(df.describe()) print(df)
语文 0 英语 0 数学 1 总分 1 dtype: int64 语文 英语 数学 总分 count 5.000000 5.000000 4.000000 4.000000 mean 84.800000 84.000000 90.250000 268.500000 std 11.987493 10.931606 9.464847 12.922848 min 66.000000 65.000000 77.000000 255.000000 25% 80.000000 85.000000 86.750000 258.750000 50% 90.000000 88.000000 93.000000 269.000000 75% 93.000000 90.000000 96.500000 278.750000 max 95.000000 92.000000 98.000000 281.000000 语文 英语 数学 总分 赵云 93.0 92.0 96.0 281.0 关羽 95.0 85.0 98.0 278.0 典韦 80.0 90.0 90.0 260.0 黄忠 90.0 88.0 77.0 255.0 张飞 66.0 65.0 NaN NaN 语文 0 英语 0 数学 0 总分 0 dtype: int64 语文 英语 数学 总分 count 5.000000 5.000000 5.000000 5.000000 mean 84.800000 84.000000 90.250000 259.050000 std 11.987493 10.931606 8.196798 23.911556 min 66.000000 65.000000 77.000000 221.250000 25% 80.000000 85.000000 90.000000 255.000000 50% 90.000000 88.000000 90.250000 260.000000 75% 93.000000 90.000000 96.000000 278.000000 max 95.000000 92.000000 98.000000 281.000000 语文 英语 数学 总分 赵云 93.0 92.0 96.00 281.00 关羽 95.0 85.0 98.00 278.00 典韦 80.0 90.0 90.00 260.00 黄忠 90.0 88.0 77.00 255.00 张飞 66.0 65.0 90.25 221.25
联系客服