pandas的增删改查

 

import pandas as pd

data = pd.Series([1,2,3],index=['a','b','c'])

1.增

1 )像字典一样直接添加

data['d'] = 4

data
Out[70]:
a 1
b 2
c 3
d 4

data原函数改变,增加对应的值

2)data.append()

注意两点:1.append()内需要添加pd.Series元素

      2.append添加元素后,原函数没有改变(这点区分字典)

data.append(pd.Series([5],index=['e'])

Out[71]:
a 1
b 2
c 3
d 4
e 5
dtype: int64

 

data
Out[72]:
a 1
b 2
c 3
d 4
dtype: int64

 

s1 = pd.Series([1,2,3])

 s2  =pd.Series([4,5,6,7])

s3 = pd.Series([4,5,6],index=[5,6,7])

 


s1.append(s2)
Out[57]: 
0 1
1 2
2 3
0 4                                注意新添加的数据的索引从0开始重新填写
1 5
2 6
3 7
dtype: int64

 

In [62]: s1.append(s3)

Out[62]: 

0 1

1 2

2 3

5 4                            添加的索引为s3已经定义好的索引

6 5

7 6

 

In [63]: s1.append(s2, ignore_index=True)

Out[63]: 

0 1

1 2

2 3

3 4                                 如果添加 ignore_index=True,那么索引会自动按顺序添加

4 5

5 6

dtype: int64

2.删

三种:1.del  2.pop()  3.drop()

1)del

原函数'a'被删除

del data['a']

data
Out[75]:
b 2
c 3
d 4
dtype: int64

2)pop()

得到一个返回值,原函数'b'被删除

pop的一个小应用   :    data['e']=data.pop('d')  将索引'd' 改为'e'

data.pop('b')

Out[76]: 2

data
Out[77]:
c 3
d 4
dtype: int64

3)drop()

注意:使用drop,原函数没有删除(字典里没有drop,注意区别)


data.drop('c')
Out[79]:
d 4
dtype: int64

data
Out[80]:
c 3
d 4
dtype: int64

3.改

1)像字典一样改值

data['c']=66

data
Out[82]:
c 66
d 4
dtype: int64

2)update

注意点:update内部必须是Series函数

更新多个数据

datas_pys.update(pd.Series([2,3,4],index = ['want','to','do']))

datas_pys
Out[44]: 
i 0
want 2
to 3
do 4
dtype: int32

更新单个数据

datas_pys.update(pd.Series([11],index=['to']))

datas_pys
Out[49]: 
i 0
want 2
to 11
do 4
dtype: int32

3)索引的修改

注意:修改必须所有索引一起修改

data.index = ['a','b']

Out[107]:
a 33
b 4
dtype: int64

4.查

1)像字典一样直接查看

data['a']

Out[108]: 33

2)values查看所有值


data.values
Out[109]: array([33, 4], dtype=int64)

3)获取索引值

data.index

Out[110]: Index(['a', 'b'], dtype='object')

posted on 2018-04-02 21:37  风过竹影  阅读(2768)  评论(0编辑  收藏  举报