本博客代码主要关于Pandas的基本介绍以及选择数据和切片数据 ########Pandas#############有点像字典 #################Pandas的基本介绍###################### import pandas as pd import numpy as np s=pd.Series([1,3,6,np.nan,44,1])#列表的index标签,自动加上序号 print(s) dates=pd.date_range('20241004', periods=6)#从10月4开始创建的六个序列 print(dates) df=pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d'])#三步:①生成一个随机序列6行四列②行名称为dates定义的③列名称为abcd print(df) df1=pd.DataFrame(np.arange(12).reshape(3,4))#随机生成序列但是没有加序号会自动加上序号 df2=pd.DataFrame({'A':1,'B':pd.Timestamp('20241004'),'C':pd.Series(1,index=list(range(4)),dtype='float32'),'D':np.array([3]*4,dtype='float32'),'E':pd.Categorical(["TEST","TRAIN","TEST","TRAIN"]),'f':'FOO'}) #df2自定义相关矩阵 print(df1) print(df2) print(df2.dtypes)#查看df2的类型 print(df2.index)#查看df2的序号行号 print(df2.columns)#查看df2的列号 print(df2.values)#查看df2的值 print(df2.describe())#运算数字的平均值等相关 print(df2.T)#矩阵转置 print(df2.sort_index(axis=1,ascending=False))#对列号倒序排序 print(df2.index)#查看df2的序号行号 print(df2.sort_index(axis=0,ascending=False))#对行号倒序排序 print(df2.sort_values(by='E'))#对单行的值进行排序 ###################Pandas选择数据####################### dates1=pd.date_range("20241004",periods=6) df3=pd.DataFrame(np.arange(24).reshape((6,4)),index=dates1,columns=['a','b','c','d']) print(df3['a'],df3.a)#打印a对应的那列 print(df3[0:2],df3['20241004':'20241005'])#打印切片选择前两行 #select by label:loc纯标签筛选 print(df3.loc['20241004'])#以标签形式选择 print(df3.loc[:,['a','b']])#筛选列 print(df3.loc['20241004',['a','b']])#筛选列和行混合 #select by position:iloc纯数字筛选 print(df3.iloc[3])#打印第三行的数据 print(df3.iloc[3,1])#打印第三行,第一位 print(df3.iloc[3:5,1])#切片 print(df3.iloc[[1,3,5],1:3])#不连续切片 #Boolean indexing print(df3) print(df3[df3.a>8])#在a这列筛选大于8的部分,并且也显示其他部分
Python小白之Pandas1
2025/4/19 14:39:51
来源:https://blog.csdn.net/m0_52094641/article/details/142703179
浏览:
次
关键词:Python小白之Pandas1
版权声明:
本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。
我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com