Pandas基础

Pandas基础

  1. 文件读取与写入
  2. 基本数据结构
  3. 常用基本函数
  4. 排序
1.文件读取与写入

1.1 读取

csv格式

df = pd.read_csv('data/table.csv')
df.head()

txt格式

df_txt = pd.read_table('data/table.txt') #可设置sep分隔符参数
df_txt

xls或xlsx格式
需要安装xlrd包

df_excel = pd.read_excel('data/table.xlsx')
df_excel.head()

1.2 写入
csv格式

df.to_csv('data/new_table.csv')

xls或xlsx格式
需安装openyxl

df.to_excel('data/new_table2.xlsx', sheet_name='Sheet1')
2 基本数据结构

2.1 Series
对于一个Series,其中最常用的属性为值(values),索引(index),名字(name),类型(dtype)

a.创建一个Series

s = pd.Series(np.random.randn(5),index=['a','b','c','d','e'],name='这是一个Series',dtype='float64')
s

b.访问Series属性

s.values
s.name
s.index
s.dtype

c.取出某一个元素

s['a']

d.调用方法

s.mean()
#Series有相当多的方法可以调用:
print([attr for attr in dir(s) if not attr.startswith('_')])

2.2Dataframe
a.创建一个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

b.从Dataframe取出一列为Series

df['col1']
type(df)
type(df['col1'])

c.修改列名或行名

df.rename(index={'一':'one'},columns={'col1':'new_col1'})

d.调用属性和方法

df.index
df.columns
df.values
df.shape
df.mean()

e.索引引齐特性
这是Pandas中非常强大的特性,不理解这一特性有时就会造成一些麻烦

df1 = pd.DataFrame({'A':[1,2,3]},index=[1,2,3])
df2 = pd.DataFrame({'A':[1,2,3]},index=[3,1,2])
df1-df2

f.列的删除与添加
对于删除而言,可以使用drop函数或del或pop函数

df.drop(index='五',columns='col1')
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方法
df1['B']=list('abc')
df1
df1.assign(C=pd.Series(list('def')))
#但assign方法不会对原DataFrame做修改
df1

g.根据类型选择列

df.select_dtypes(include=['number']).head()
df.select_dtypes(include=['float']).head()

h。将Series转换为DataFrame

s = df.mean()
s.name='to_DataFrame'
s
s.to_frame()
#使用T符号可以转置
s.to_frame().T
3 常用基本函数

为了保持方便,采用一份虚拟的数据集

df = pd.read_csv('data/table.csv')

3.1 head和tail

df.head()
df.tail()
#可以指定n参数显示多少行
df.head(3)

3.2 unique和nunique
nunique显示有多少个唯一值,unique显示所有的唯一值

df['Physics'].nunique()
df['Physics'].unique()

3.3 count和value_counts
count返回非缺失值元素个数,value_counts返回每个元素有多少个

df['Physics'].count()
df['Physics'].value_counts()

3.4 describe和info
info函数返回有哪些列、有多少非缺失值、每列的类型,describe默认统计数值型数据的各个统计量

df.info()
df.describe()
#可以自行选择分位数
df.describe(percentiles=[.05, .25, .75, .95])
#对于非数值型也可以用describe函数
df['Physics'].describe()

3.5 idxmax和nlargest
idxmax函数返回最大值,在某些情况下特别适用,idxmin功能类似,nlargest函数返回前几个大的元素值,nsmallest功能类似

df['Math'].idxmax()
df['Math'].nlargest(3)

3.6 clip和replace
clip和replace是两类替换函数,

#clip是对超过或者低于某些值的数进行截断
df['Math'].head()
df['Math'].clip(33,80).head()
df['Math'].mad()
#replace是对某些值进行替换
df['Address'].head()
df['Address'].replace(['street_1','street_2'],['one','two']).head()
#通过字典,可以直接在表中修改
df.replace({'Address':{'street_1':'one','street_2':'two'}}).head()

3.7 apply函数
apply是一个自由度很高的函数

#对于Series,它可以迭代每一列的值操作:
df['Math'].apply(lambda x:str(x)+'!').head()
#对于DataFrame,它可以迭代每一个列操作
df.apply(lambda x:x.apply(lambda x:str(x)+'!')).head()
4 排序

4.1 索引排序

df.set_index('Math').head()
df.set_index('Math').sort_index().head()

4.2 值排序

df.sort_values(by='Class').head()
#多个值排序,即先对第一层排,在第一层相同的情况下对第二层排序
df.sort_values(by=['Address','Height']).head()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值