pandas基本操作

Series对象

#创建一个Series
s = pd.Series([1,3,6,np.nan,44,1])

Index对象

#创建一个index
dates = pd.date_range('20190101',periods=6)

s输出
0 1.0
1 3.0
2 6.0
3 NaN
4 44.0
5 1.0
dtype: float64

DataFrame对象

#dataFrame是一个行和列的Matrix,index是行的索引,columns是列的索引,默认是从0开始的数字
#np.random.randn是产生随机数,这些随机数是服从normal distribution的
df = pd.DataFrame(np.arange(24).reshape(6,4),index=dates,columns=['A','B','C','D'])
image.png

读取文件并查看前5行

import pandas as pd

data = pd.read_csv('student.csv')
print(data)

存储文件(pickle)

data.to_pickle('student.pickle')

查询操作

打印列

df['A']
df.A
image.png

打印列中没有重复的值

set(df['A'])
pd.unique(df['A'])

打印0-3行

df[0-3]
image.png

select by label: df.loc()

loc查找的是标签的label,用0,1这种索引号是不行的,必须用label

print(df.loc[:,['A','B']])
df.loc['2019-01-02':'2019-01-04','A':'C']
df.loc[:,['A','B']] df.loc['2019-01-02':'2019-01-04','A':'C']
image.png
image.png

#select by position: iloc

iloc:indexLoc,就是用索引号来查找,不是标签

print(df.iloc[0:3,0:3])#切片操作
#选择不连续的数据
print(df.iloc[[1,3,5],0:3])
df.iloc[0:3,0:3] df.iloc[[1,3,5],0:3]
df.iloc[0:3,0:3]
df.iloc[[1,3,5],0:3]

使用布尔索引进行选择筛选(BooleanIndex)

print(df[df.A > 8])
1
1 2
1
2

只能用loc使用布尔索引,用iloc会报错

data.loc[data.loc[:,"MonthlyIncome"].isnull(),"MonthlyIncome"]

使用上面代码查询出来的结果是:本次查询的意思是要查询的行使用布尔索引,以data.loc[:,"MonthlyIncome"].isnull()为查询条件,然后将True的记录查询出来;要查询的列是MonthlyIncome。
查出来的就是MonthlyIncome为NaN的那些记录。

image.png

data.loc[:,"MonthlyIncome"].isnull()

上端代码的输出是一些布尔值。


data.loc[:,"MonthlyIncome"].isnull()

在末尾新增一列

df['D'] = [1,2,3,4,5,6]
df['F'] = np.NAN #跟新增字典记录差不多
print(df)
image.png

指定位置增加行

df.insert(0,'E',[11,12,13,14,15])
image.png

用loc指定位置添加一行

df.loc[2019-01-07]=[9,10,11,12,13,14,15,16]

处理空值

把NAN值都填充为0

print(df.fillna(value=0))
image.png

对有缺失值的记录进行删除

print(df.dropna(axis=0,how='all'))#只有这个行里所有的数据都是NAN才drop掉
print(df.dropna(axis=0,how='any'))#只要有一个为NAN就整行丢掉

print(df.dropna(axis=1,how='all'))#整列全都为NAN时才将这列删掉
print(df.dropna(axis=1,how='any'))#有一个NAN就整列删掉

原数据

方式 axis=0 axis=1
how='all'
image.png
image.png
hoe='any'
image.png
image.png

concatenating级联【数据合并】

相同字段的表首尾相接

#属性都是一样的,需要上下合并,会存在index重复的问题,可使用ignore_index
result = pd.concat([df1,df2,df3],axis=0,ignore_index=1)
image.png

横向表拼接(行对齐)

如果有join_axes的参数传入,可以指定根据那个轴来对齐数据
例如根据df1表对齐数据,就会保留指定的df1表的轴,然后将df4的表与之拼接

result = pd.concat([df1, df4], axis=1, join_axes=[df1.index])
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容