1 pandas数据读取
Pandas需要先读取表格类型的数据,然后进行分析
1.1 阅读文件和基本语句:
import pandas as pd filepatch=r"C:\Users\radiomumm\Desktop\sucai\nba.csv" #读取csv文件数据 ratings=pd.read_csv(filepatch) #查看文件开头的几行 print(ratings.head()) #查看文件行列属性,(行,列) print(ratings.shape) #查看列名,返回列表 print(ratings.columns) #查看索引列 print(ratings.index) ##查看每列数据的数据类型 print(ratings.dtypes)
import pandas as pd filepatch=r"C:\Users\radiomumm\Desktop\sucai\nba.txt" #
自定义读取文件,sep=设置分隔符,header=设置标题行是否行,names=设置自定义列名。 ratings=pd.read_csv(filepatch,sep="\t",header=None,names=['NAME', 'state']) print(ratings.head())
import pandas as pd filepatch=r"C:\Users\radiomumm\Desktop\sucai\bhlh112.xlsx" ratings=pd.read_excel(filepatch) print(ratings.head())
2 pandas数据结构(dataframe & series)
:二维数据,整个表格,多行多列。
:一维数据代表一行或一列。包括一组数据(不同数据类型)和一组相关数据标签(索引)。
3 创建Series或Dataframe
3.1 series:
3.1.1 列表创建series:
import pandas as pd sl=pd.Series([1,"A",23,5.4])
# [out]
# 0 1
# 1 A
# 2 23
# 3 5.4
# dtype: object
#获取索引
print(sl.index)#"RangeIndex(start=0, stop=4, step=1)"
# 获取值数列
print(sl.values)#[1 'A' 23 5.4]
#更换索引列,创建一个具有标签的Series.
sl=pd.Series([1,"A",23,5.4],index=["a","b","c","d"])
print(sl.index)#Index(['a', 'b', 'c', 'd'], dtype='object')
3.1.2 字典创建series:
#使用字典创建Series
dictdata={
"a":123,"b":3234,"c":1.2,"d":"end"}
sl2=pd.Series(dictdata)
print(sl2)
# [out]
# a 123
# b 3234
# c 1.2
# d end
# dtype: object
3.1.3 查询Series中的数据
print(sl2["a"])#查询一个值时,返回原生数据。
print(sl2[["a","b"]])#查询两个值时,返回一个Series。
3.2 Dataframe
3.2.1 创建Dataframe:
①.常见的方法为第一章中的Pandas读取excel/csv/mysql
②.使用多个字典文件创建Dataframe
import pandas as pd
dataf={
"name":["xiaohong","xiaozhang","xiangqiang"],
"age":[21,23,22],
"gender":["female","male","female"],
"school":["1s","3s","2s"]}
df=pd.DataFrame(dataf)
print(df)
# [out]
# name age gender school
# 0 xiaohong 21 female 1s
# 1 xiaozhang 23 male 3s
# 2 xiangqiang 22 female 2s
print(df.index)#RangeIndex(start=0, stop=3, step=1)
print(df.columns)#Index(['name', 'age', 'gender', 'school'], dtype='object')
3.2.2 查询Dataframe中的数据:
如果只查询一列、一行,返回的是Series。
如果查询的说多列、多行,返回的是一个Dataframe。
print(df["age"])#返回的是Series
print(df[["age"]])#返回的是Dataframe
print(df[["age","school"]])
4.1 loc和iloc的用法
loc 基于行标签和列标签(x_label、y_label)进行索引,主要查询方法:
1.使用单个labe伯查询数据
2.使用值列表批查询
3.使用数伯区间进行范围查询
4.使用条件太达式查向
5.调用函数查询
loc先行后列,中间用逗号(,)分割。
4.1.1.0 数据准备
传入NBA球员薪资情况表:
import pandas as pd
# 0.数据的预处理
filepatch=r"C:\Users\radiomumm\Desktop\sucai\nba.csv"
#读取csv文件数据
df=pd.read_csv(filepatch)
#设置列索引,inplace=True直接改变df格式
df.set_index("NAME",inplace=True)
#将"SALSRY"中的"$45,780,966"格式修改为"45780966"数值格式,以便于就绪操作。
df.loc[:,"SALSRY"]=df["SALSRY"].str.replace("$","").str.replace(",","").astype("int32")
# 查询"Stephen Curry, PG"的薪资
print(df.loc["Stephen Curry, PG","SALSRY"])#返回单一值,"45780966"
# 查询"Stephen Curry, PG"的薪资和队伍
print(df.loc["Stephen Curry, PG",["SALSRY","TEAM"]])#返回一个Series
使用值列表批量查询数据
# 查询"Stephen Curry, PG"/"James Harden, SG"/"John Wall, PG"的薪资
print(df.loc[["Stephen Curry, PG","James Harden, SG","John Wall, PG"],"SALSRY"])#得到一个series
print(df.loc[["Stephen Curry, PG","James Harden, SG","John Wall, PG"],["SALSRY","TEAM"]])#得到一个Dataframe
使用数值区间批量查询数据
【区间既包含开始,也包含结束】
print(df.loc["Stephen Curry, PG":"John Wall, PG","SALSRY"])#行index查询,前三行的薪资
print(df.loc["Stephen Curry, PG","TEAM":"SALSRY"])#列index查询,第一行的两列数据
print(df.loc["Stephen Curry, PG":"John Wall, PG","TEAM":"SALSRY"])#行和列同时使用区间查询
使用条件表达式查询
【bool列表的长度得等于行数或者列数】
# 查询薪资大于41018900的球员
print(df.loc[df["SALSRY"]>41018900,:])
# 查询薪资大于41018900的球员,且在"Los Angeles Lakers"队中。【每个条件由括号分隔】
print(df.loc[(df["SALSRY"]>41018900)&(df["TEAM"]=="Los Angeles Lakers"),:])
使用函数查询
# 直接调用lambda函数,输入整个df,然后按条件筛选。
print(df.loc[lambda df :(df["SALSRY"]>41018900)&(df["TEAM"]=="Los Angeles Lakers"),:])
# 编写自己的函数进行查询,所有属于"Golden State Warriors"队的球员
def choose_maydata(df):
return df["TEAM"]=="Golden State Warriors"
print(df.loc[choose_maydata,:])
4.1.2 iloc
iloc 基于行索引和列索引(index,columns)都是从 0 开始
如果数据的行标签和列标签名字太长或不容易记,则用 iloc 很方便,只需记标签对应的索引即可。
print(df.iloc[0,2])#取出Stephen Curry, PG的薪资数据,"45780966"
print(df.iloc[0:2])#取前两行对应数据
print(df.iloc[:,0:2])#取前两列对应数据
print(df.iloc[0:2,0:2])#取前两行和前两列对应数据
print(df.iloc[[0,2],[0,1,2]])#取第一行和第三行、第一列和第四列对应的数据
5 Pandas新增数据列
【直接赋值/apply/assign/分条件赋值】
5.0 数据预处理
import pandas as pd
# 0.数据的预处理
filepatch=r"C:\Users\radiomumm\Desktop\sucai\nba.csv"
#读取csv文件数据
df=pd.read_csv(filepatch)
直接赋值
和上文提到的修改数值方法相同,将Series格式看作为dictionary直接赋值。
# 选中df中的"SALSRY"列,对改列进行重新赋值,赋值内容为去除"$"和","并转化为int32格式
df.loc[:,"SALSRY"]=df["SALSRY"].str.replace("$","").str.replace(",","").astype("int32")
# 新增列,球员上场位置。
df.loc[:,"positions_TYPE"]=df["NAME"].str.replace("\w* \w*,","")
# 修改球员名字后的上场位置。
df.loc[:,"NAME"]=df["NAME"].str.replace(",.*","")
5.2 df.apply方法
这个函数需要自己实现,函数的传入参数根据axis来定,比如axis = 1,就会把一行数据作为Series的数据结构传入给自己实现的函数中,我们在函数中实现对Series不同属性之间的计算,返回一个结果,则apply函数 会自动遍历每一行DataFrame的数据,最后将所有结果组合成一个Series数据结构并返回。
实例:添加一列实例:薪资大于40000000的为高薪,低于10500000的为底薪,否则就是正常薪资。
def get_SALSRY(df):
if df["SALSRY"]>=40000000:
return "high"
elif df["SALSRY"]<=10500000:
return "low"
else:
return "normal"
df.loc[:,"hight_low"]=df.apply(get_SALSRY,axis=1)#第0轴沿着行的垂直往下,第1轴沿着列的方向水平延伸。
#使用value_counts()函数对该列进行计数
x=df["hight_low"].value_counts()
print(x)
5.3 df.assign方法
能够同时新增多个列,返回一个新列,该对象除新列外,还包含所有原始列。【assgin不会改变原有df,因此需要重新赋值】
实例:添加一列球员人民币薪资
df=df.assign(RMB=lambda x :x["SALSRY"]*6.72)
5.4 按条件选择分组分别赋值
按条件先选择数据,然后对这部分数据赋值新列
实例:PG球员薪资超过30000000认为是球星。
df["superstar"]=""
df.loc[df["SALSRY"]>=30000000,"superstar"]="star"
df.loc[df["SALSRY"]<30000000,"superstar"]="normal_player"
# print(df.head(120))
x=df["superstar"].value_counts()
print(x)
6 Pandas对缺值的处理
三类函数完成以上操作:
●isnll和notnull: 检测是否是空值,可用于df和series。
●dropna: 丢弃、删除缺失值
axis :删除行还是列,{0 or "index', 1 or 'columns’}, default 0
how :如果等于any则任何值为空都删除,如果等于al则所有值都为空才删除。
inplace :如果为True则修改当前df,否则返回新的df。
●fllna: 填充空值
value:用于填充的值,可以是单个值,或者字典(key是列名,value是值)。
method :等于il使用前一个不为空的值填充forword fll;等于bil使用后一个不为空的值填充backword fill。
axis: 按行还是列填充,{0 or index', 1 or 'columns'}
inplace :如果为True则修改当前df,否则返回新的df。
6.0 准备数据
录入qPCR的分析数据(excel):
其中skiprows=num这一参数能够忽略设置的行数,即skiprows=1:忽略第一行。
import pandas as pd
filepatch=r"C:\Users\radiomumm\Desktop\sucai\qpcr.xlsx"
df=pd.read_excel(filepatch,skiprows=1)#skiprows=num,忽略前num行读取。
检测数据集中的空值
isnull返回的值均为True/False,适用于Dataframe和Series。
print(df.isnull())#返回整个Datafream中True/False,对应是否为空值。
print(df["SAMPLE"].isnull())#返回Series中True/False,对应是否为空值。
notull可用于筛选所有不为空值的行列
print(df.notnull())#返回整个Datafream中True/False,对应是否不为空值,与isnull函数相反。
print(df["SAMPLE"].notnull())#返回Series中True/False,对应是否不为空值,与isnull函数相反。
print(df.loc[df["A1"].notnull(),:])#筛选"A1"列不为空的所有行
删除空值的列
dropna函数中axis="columns"表示列删除,how="all"表示删除全为空值的列,inplace=True表示对数据集本身进行修改。
axis参数:存在"columns"和"index"两种模式。即,一个删除列一个删除行。
how参数:存在"all"和"any"两种模式。使用"all"时删除全部为空值模式;使用"any"时为存在空值就删除模式。
df.dropna(axis="columns",how="all",inplace=True)
df.dropna(axis="index",how="all",inplace=True)
6.4 空值
使用fillna函数对空值进行填充,需要用到inplace=True对原Dataframe进行修改。
对单一Series进行填充
df.fillna({
"A1":0},inplace=True)
对多个Series进行填充
df.fillna({
"A1":"NA","A2":"NA","A3":"NA","ACT1":"NA","ACT2":"NA","ACT3":"NA"},inplace=True)#实现多行填充
6.5 将某列中的空值填充为上一个元素
这里用到了fillna中的参数:ffill(forward fill)。即使用前面不为空的值进行填充。
df.loc[:,"NAME"]=df["NAME"].fillna(method="ffill")
df.loc[:,"SAMPLE"]=df["SAMPLE"].fillna(method="ffill")
6.6 将清洗好的excel保存为新的文件
使用to_excel将数据保存为新的excel,保存时添加index=False能够避免生成行数列。
df.to_excel(r"C:\Users\radiomumm\Desktop\sucai\qpcr_clean.xlsx",index=False)
除to_excel外还有:
7 Pandas对数据进行排序
#数据的预处理
import pandas as pd
filepatch=r"C:\Users\radiomumm\Desktop\sucai\nba.csv"
df=pd.read_csv(filepatch)
df.loc[:,"SALSRY"]=df["SALSRY"].str.replace("$","").str.replace(",","").astype("int32")
7.1 Series的排序
参数:
- ascencding: 默认为True升序排序,为False降序排序。
- inplace: 是否修改原始Series。 排序时对数值和字符串均能排序,数值默认升序,字符串默认a-z。
print(df["SALSRY"].sort_values())#默认为True升序排序
print(df["SALSRY"].sort_values(ascending=False))#False降序排序
print(df["TEAM"].sort_values())#字符串同样能够排序,默认为a-z
7.2 DataFrame的排序
参数 :
- by: 字符串或者List<字符串>, 单列排序或者多列排序。
- ascending: bool或者List, 升序还是降序,如果是list对应by的多列。
- inplace: 是否修改原始DataFrame 事实上DF是以某一列或某几列对整个数据集按行排序。
print(df.sort_values(by="SALSRY"))#以SALSRY列对整个df进行排序,默认为True升序排序
print(df.sort_values(by="SALSRY",ascending=False))#以SALSRY列对整个df进行排序,默认为True升序排序
print(df.sort_values(by=["TEAM","SALSRY"],ascending=False))#先排"TEAM"再排"SALSRY"
print(df.sort_values(by=["SALSRY","TEAM"],ascending=False))
print(df.sort_values(by=["TEAM","SALSRY"],ascending=[False,True]))
8 Pandas中字符串的处理
pandas提供大量关于字符串常用方法:
https://pandas.pydata.org/docs/reference/series.html#string-handling
具体使用方法 :
-
使用方法:先获取Series的str属性, 然后在属性上调用函数。
-
只能在字符串列上使用,不能数字列上使用。
-
Dataframe.上没有str属性和处理方法。
-
Series.str并不是Python原生字符串,而是自己的一套方法,不过大部分和原生str很相似。 本节只挑选常用的部分语句演示:
-
获取Series的str属性,然后使用各种字符串处理函数
-
使用str的startswith、contains等bool类Series可以做条件查询
-
需要多次str处理的链式操作
-
使用正则表达式的处理
8.0 准备数据
import pandas as pd
filepatch=r"C:\Users\radiomumm\Desktop\sucai\nba.csv"
df=pd.read_csv(filepatch)
8.1 替换字符串中的内容
使用replace函数,批量替换series中的特定字符串。
print(df["SALSRY"].str.replace("$","").str.replace(",",""))
8.2 使用str的startswith、contains等得到bool的Series可以做条件查询
condition=df["NAME"].str.startswith("Stephen")
# print((condition))#返回只含有True/False的bool series
print(df[condition])#返回筛选结果
8.3 多次替换并截取字符串中的内容
print(df["NAME"].str.replace(", ","-").str.slice(-2))#其中slice就是切片用法,slice[-2] #相当于 print(df["NAME"].str.replace 标签:
ross高继电器e12