pandas的series的增删改查(5)

CURD的意思同数据库中一样,是创建、更新、读取和删除的意思。

5.1创建Series

标准的创建Series的方式是用字符串列表作为Series对象的标识每个数据的方式,即label来标志出每个数据。

import pandas as pd
idx = "hello the cruel world".split()
val = range(10, 14)
s = pd.Series(val, index = idx)
print s

创建的Series对象s为:

hello    10
the      11
cruel    12
world    13
dtype: int64

5.2 读取数据

读取series对象的label和value的方式有很多。

  • 通过label或者位置的方式访问、修改Series数据。
import pandas as pd
idx = "hello the cruel world".split()
val = range(10, 14)
s = pd.Series(val, index = idx)
print s
print s["hello"]
s["hello"] = 100
s[1] = 110
print s
  • iteritems函数可以获得标签和值。
import pandas as pd
idx = "hello the cruel world".split()
val = range(10, 14)
s = pd.Series(val, index = idx)

for x in s.iteritems():
    print x

程序的执行结果如下:

('hello', 10)
('the', 11)
('cruel', 12)
('world', 13)

5.3 修改数据

  • 可以通过label或位置信息修改对应的数据,例如上边程序里的
s["hello"] = 100
s[1] = 110
  • 当然也可用iloc、loc、at、iat等来处理。
import pandas as pd
idx = "hello the cruel world".split()
val = range(10, 14)
s = pd.Series(val, index = idx)
print s
s[0] = 100
s.loc["the"] = 101
s.at['cruel'] = 201
s.ix[3] = 300
print s

程序的执行结果如下:

hello    10
the      11
cruel    12
world    13
dtype: int64
hello    100
the      101
cruel    201
world    300
dtype: int64

5.4 增加数据

  • 通过append、set_value函数为series增加数据。
import pandas as pd
idx = "hello the cruel world".split()
val = range(10, 14)
s = pd.Series(val, index = idx)
print s, "<-org"
s = s.append(pd.Series({"this":9}))
s = s.append(pd.Series({"this":10}))
print s, "<-append"
s.set_value("this", 8)
print s, "<-set_value"

程序执行结果:

hello    10
the      11
cruel    12
world    13
dtype: int64 <-org
hello    10
the      11
cruel    12
world    13
this      9
this     10
dtype: int64 <-append
hello    10
the      11
cruel    12
world    13
this      8
this      8
dtype: int64 <-set_value

在Series里是允许label相同的。

5.5 删除数据

删除在Series很少用。常用布尔选择或mask来选择数据组成新的Series。

import pandas as pd
idx = "hello the cruel world".split()
val = range(10, 14)
s = pd.Series(val, index = idx)
print s, "<-org"
t = s[s > 11]
print t,"<- bool sel"
print s,"<- still"

执行结果:

hello    10
the      11
cruel    12
world    13
dtype: int64 <-org
cruel    12
world    13
dtype: int64 <- bool sel
hello    10
the      11
cruel    12
world    13
dtype: int64 <- still

新生成的t是通过t = s[s > 11]语句得到的(布尔选择),而s没有变化。t为:

cruel    12
world    13
dtype: int64 <- bool sel
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值