目录
一、pandas学习准备
1.python中安装pandas库,pip install pandas,为避免因超时导致装载失败,可采用国内镜像安装库,具体方法可参见link,如果项目不急可选择清晨安装,网络比较稳定。
2.安装xlrd包、openpyxl包(分别为读取和写入excel文件时用到)
3.准备好需要操作的文件
4.导入需要用到的库
import pandas as pd
import numpy as np
二、文件读写
读取、写入csv格式
df = pd.read_csv('data/table.csv')
df.head()
df.to_csv('data/new_table.csv')
#df.to_csv('data/new_table.csv', index=False) #保存时除去行索引
读取、写入txt格式
df_txt = pd.read_table('data/table.txt') #可设置sep分隔符参数
df_txt
df_txt.to_csv('data/new_table.txt', index=False)
读取、写入xls或xlsx格式
#需要安装xlrd包
df_excel = pd.read_excel('data/table.xlsx')
df_excel.head()
#需要安装openpyxl
df.to_excel('data/new_table2.xlsx', sheet_name='Sheet1')
三、基本数据结构
1.series
对于一个Series,其中最常用的属性为值(values),索引(index),名字(name),类型(dtype)
(1)series创建
s = pd.Series(np.random.randn(5),index=['a','b','c','d','e'],name='这是一个Series',dtype='float64')
s
(2)访问Series属性
s.values
s.name
s.index
s.dtype
(3)调用方法
#取平均值
s.mean()
#Series有相当多的方法可以调用
print([attr for attr in dir(s) if not attr.startswith('_')])
2.DataFrame
(1)数据框DataFrame创建
df = pd.DataFrame({'col1':list('abcde'),'col2':range(5,10),'col3':[1.3,2.5,3.6,4.6,5.8]},
index=list('一二三四五'))
df
(2)修改行或列名
df.rename(index={'一':'one'},columns={'col1':'new_col1'})
(3)调用属性和方法
df.index
df.columns
df.values
df.shape
df.mean()
(4)索引对其特性
#由于索引默认对齐,因此结果是0
df1 = pd.DataFrame({'A':[1,2,3]})
df2 = pd.DataFrame({'A':[1,2,3]})
df1-df2
#由于索引对齐,因此结果不是0
df1 = pd.DataFrame({'A':[1,2,3]},index=[1,2,3])
df2 = pd.DataFrame({'A':[1,2,3]},index=[3,1,2])
df1-df2
(5)列的删除与添加
删除,可以使用drop函数或del或pop
df.drop(index='五',columns='col1') #设置inplace=True后会直接在原DataFrame中改动
df['col1']=[1,2,3,4,5]
del df['col1']
df
#pop方法直接在原来的DataFrame上操作,且返回被删除的列,与python中的pop函数类似
df['col1']=[1,2,3,4,5]
df.pop('col1')
df
添加,可以直接增加新的列,也可以使用assign方法,但assign方法不会对原DataFrame做修改,需要自行保存一下
df1['B']=list('abc')
df1
df1.assign(C=pd.Series(list('def')))
df1
(6)根据类型选择列
df.select_dtypes(include=['number']).head()
df.select_dtypes(include=['float']).head()
(7)将Series转换为DataFrame
s = df.mean()
s.name='to_DataFrame'
s
(8)使用T符号可以转置
s.to_frame().T
四、常用基本函数
df = pd.read_csv('data/table.csv')
1.head和tail
head和tail可以指定n参数显示多少行,head是从前往后,tail是从后往前。默认为5
df.head()
df.tail()
2. nunique和unique
nunique显示有多少个唯一值,unique显示所有的唯一值。
df['Physics'].nunique()
df['Physics'].unique()
3. count和value_counts
count返回非缺失值元素个数,value_counts返回每个元素有多少个(不包括缺失值对应情况)。
df['Physics'].count()
df['Physics'].value_counts()
4.describe和info
info函数返回有哪些列、有多少非缺失值、每列的类型,describe默认统计数值型数据的各个统计量
df.info()
df.describe()
5. idxmax和nlargest
idxmax函数返回最大值,在某些情况下特别适用,idxmin功能类似;nlargest函数返回前几个大的元素值,nsmallest功能类似
df['Math'].idxmax()
df['Math'].nlargest(3)
6. clip和replace
clip和replace是两类替换函数
clip是对超过或者低于某些值的数进行截断
replace是对某些值进行替换
通过字典,可以直接在表中修改
df['Math'].head()
df['Math'].clip(33,80).head()
df['Math'].mad()
df['Address'].head()
df['Address'].replace(['street_1','street_2'],['one','two']).head()
df.replace({'Address':{'street_1':'one','street_2':'two'}}).head()
7. apply函数
apply是一个自由度很高的函数
对于Series,它可以迭代每一列的值操作
对于DataFrame,它可以迭代每一个列操作
df['Math'].apply(lambda x:str(x)+'!').head() #可以使用lambda表达式,也可以使用函数
df.apply(lambda x:x.apply(lambda x:str(x)+'!')).head() #这是一个稍显复杂的例子,有利于理解apply的功能
五、排序
1. 索引排序
df.set_index('Math').head() #set_index函数可以设置索引,将在下一章详细介绍
df.set_index('Math').sort_index().head() #可以设置ascending参数,默认为升序,True
2.值排序
df.sort_values(by='Class').head()
df.sort_values(by=['Address','Height']).head()
声明:本文主要参考Datawhale主办的一期Joyful-Pandas资料