注:本博客跟随此Pandas教程进行学习,有兴趣可以学习一下。
理论部分
先来一张整体框架图:
PandasStudy0420—第一章 Pandas基础
- 一,文件读取与写入
- 1.读取
- csv格式
- txt格式
- xls或xlsx格式
- 2.写入
- csv格式
- xls或xlsx格式
- 1.读取
- 二,基本数据结构
- 1.Series
- 创建一个Series
- 常用属性
- values(值)
- index(索引)
- name(名字)
- dtype(类型)
- 访问Series属性
- 取出某一个元素
- 调用方法
- 有好多,要不断学习
- 2.DataFrame
- 创建一个DataFrame
- 从DataFrame取出一列为Series
- 修改行或列名
- 调用属性和方法
- 索引对齐特性!!!划重点
- 列的删除与添加
- 根据类型选择列
- 将Series转换为DataFrame
- 转置
- 1.Series
- 三,常用基本函数
- 1,head和tail
- 2,unique和nunique
- unique显示所有的唯一值
- nunique显示有多少个唯一值
- 3,count和value_counts
- count返回非缺失值元素个数
- value_counts返回每个元素有多少个
- 4,describe和info
- info函数返回有哪些列,有多少非缺失值,每列的类型
- describe默认统计数值型数据的各个统计量
- 5,idxmax和nlargest
- idxmax函数返回最大值,在某些情况下特别适用,idxmin功能类似
- nlargest函数返回前几个大的元素值,nsmallest功能类似
- 6,clip和replace
- clip是对超过或者低于某些值的数进行截断
- replace是对某些值进行替换
- 7,apply函数
- 四,排序
- 1,索引排序
- 2.值排序
- 多个值排序,即先对第一层排,在第一层相同的情况下对第二层排序
代码部分
import pandas as pd
import numpy as np
# 查看Pandas版本
print(pd.__version__)
# pip install pandas 安装pandas
# pip install --upgrade pandas 更新pandas
#一,文件读取与写入
# 1.读取
# 注意目录的“/”方向
# pd.read_csv 读取csv文件
df_csv=pd.read_csv('G:/OutStudying/DataScience/joyful-pandas/data/table.csv')
print(df_csv)
# pd.read_table 读取txt文件
df_txt=pd.read_table('G:/OutStudying/DataScience/joyful-pandas/data/table.txt')
print(df_txt)
# pd.read_excel 读取xls和xlsx文件
# 记得安装xlrd模块 pip install xlrd
df_excel=pd.read_excel('G:/OutStudying/DataScience/joyful-pandas/data/table.xlsx')
print(df_excel)
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
#2.写入
# 略
# 二,基本数据结构
# 1.Series
#创建series
# 对于一个Series,其中最常用的属性为值(values),索引(index),名字(name),类型(dtype)
# np.random.randn(5) 产生五个符合正态分布的数据
s=pd.Series(np.random.randn(5),index=['a','b','c','d','e'],name='这是一个Series',dtype='float64')
print(s)
print(s.values)
print(s['a'])
# 返回平均值
print(s.mean())
#2.DataFrame
df=pd.DataFrame({'col1':list('abcde'),'col2':range(5,10),'col3':[1,2.2,4.5,6.7,8.9]},index=list('一二三四五'))
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(df.apply(lambda x:x.apply(lambda y:str(y)+'!')).head() )#这是一个稍显复杂的例子,有利于理解apply的功能
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print(df)
print(df['col2'])
# 修改行或列名
df_new=df.rename(index={'二':'two'})
print(df_new)
print(df.shape)
print(df.mean())
df1=pd.DataFrame({'A':[1,2,3]},index=[1,2,3])
df2=pd.DataFrame({'A':[1,2,3]},index=[3,1,2])
# 按照索引来减并且要求列号相同
print(df1-df2)
# list索引是从0开始的 所以索引3会是Nan
df2=df1.assign(C=pd.Series(list('def')))
df2['B']=list('abc')
print(df2)
print(df.select_dtypes(include=['number']))
print(df.select_dtypes(include=['float']))
# Series 转换为DataFrame
print(s.to_frame())
# head和tail 取头跟尾的五行数据 head(num) 也可以指定取几行
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
# 显示Physics列有几种种类
print(df_csv['Physics'].nunique())
# 显示Physics列都有啥唯一值
print(df_csv['Physics'].unique())
print(df_csv['Physics'].describe())
# top 表示频率最高者
# 返回Math中最大值的id
df_csv['Math'].idxmax()
# nlargest函数返回前几个大的元素值
df_csv['Math'].nlargest(3)
# 获得Math在33到80之间的元素
print(df_csv['Math'].clip(33,80))
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
dfr=df_csv['Math'].apply(lambda x:str(x)+'!');
print(dfr)
练习题:
第一个练习题用分组写的,简单方法:
import numpy as np
import pandas as pd
df=pd.read_csv('G:/OutStudying/DataScience/joyful-pandas/data/Game_of_Thrones_Script.csv')
# 在原来DataFrame基础上增加新的一列:每行句子按空格断句的单词数
df_New=df.assign(Num_Word=df['Sentence'].apply(lambda x:len(x.split())))
#将相同名字的单词数进行相加得到一个Series
df_try=df_New.groupby('Name')['Num_Word'].sum()
# 输出Series中的单词数最大的name
print(df_try.idxmax())
第二个题跟答案差不多就不赘述了