首页 > 编程 > Python > 正文

python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)

2020-02-23 04:25:14
字体:
来源:转载
供稿:网友

前言

最近在网上搜了许多关于pandas.DataFrame的操作说明,都是一些基础的操作,但是这些操作组合起来还是比较费时间去正确操作DataFrame,花了我挺长时间去调整BUG的。我在这里做一些总结,方便你我他。感兴趣的朋友们一起来看看吧。

一、创建DataFrame的简单操作:

1、根据字典创造:

In [1]: import pandas as pdIn [3]: aa={'one':[1,2,3],'two':[2,3,4],'three':[3,4,5]}In [4]: bb=pd.DataFrame(aa)In [5]: bbOut[5]:  one three two0 1 3 21 2 4 32 3 5 4`

字典中的keys就是DataFrame里面的columns,但是没有index的值,所以需要自己设定,不设定默认是从零开始计数。

bb=pd.DataFrame(aa,index=['first','second','third'])bbOut[7]:  one three twofirst 1 3 2second 2 4 3third 3 5 4

2、从多维数组中创建

import numpy as npIn [9]: del aaIn [10]: aa=np.array([[1,2,3],[4,5,6],[7,8,9]])In [11]: aaOut[11]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])In [12]: bb=pd.DataFrame(aa)In [13]: bbOut[13]:  0 1 20 1 2 31 4 5 62 7 8 9

从多维数组中创建就需要为DataFrame赋值columns和index,否则就是默认的,很丑的。

bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])In [15]: bbOut[15]:  one two three22 1 2 333 4 5 644 7 8 9

3、用其他的DataFrame创建

bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])bbOut[15]:  one two three22 1 2 333 4 5 644 7 8 9cc=bb[['one','three']].copy()CcOut[17]:  one three22 1 333 4 644 7 9

这里的拷贝是深拷贝,改变cc中的值并不能改变bb中的值。

cc['three'][22]=5bbOut[19]:  one two three22 1 2 333 4 5 644 7 8 9ccOut[20]:  one three22 1 533 4 644 7 9

二、DataFrame的索引操作:

对于一个DataFrame来说,索引是最烦的,最易出错的。

1、索引一列或几列,比较简单:

bb['one']Out[21]: 22 133 444 7Name: one, dtype: int32

多个列名需要将输入的列名存在一个列表里,才是个collerable的变量,否则会报错。

bb[['one','three']]Out[29]:  one three22 1 333 4 644 7 9

2、索引一条记录或几条记录:

bb[1:3]Out[27]:  one two three33 4 5 644 7 8 9bb[:1]Out[28]:  one two three22 1 2 3

这里注意冒号是必须有的,否则是索引列的了。

3、索引某几列的变量的某几条记录,这个折磨了我好久:

第一种

bb.loc[[22,33]][['one','three']]Out[30]:  one three22 1 333 4 6

这种不能改变这里面的值,你只是能读值,不能写值,可能和loc()函数有关:

bb.loc[[22,33]][['one','three']]=[[2,2],[3,6]]In [32]: bbOut[32]:  one two three22 1 2 333 4 5 644 7 8 9            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表