python中的series的结构_Python:pandas中两种结构类型series和dataframe的重新索引和删除,Pythonpandas,Series,Dataframe,reindex...

pandas共有两种数据结构类型分别为series和dataframe,他们的区别和联系如下:

区别:

series,只是一个一维数据结构,它由index和value组成。

dataframe,是一个二维结构,除了拥有index和value之外,还拥有column。

联系:

dataframe由多个series组成,无论是行还是列,单独拆分出来都是一个series。

示例(省略import):

#Reindexing

>>>ser=pd.Series([2,5,7,4],index=['one','two','three','four'])

>>>print(ser)

one 2

two 5

three 7

four 4

可以对ser使用成员方法reindex修改index值,由于在Python中可变参数由引用传递,因此ser.reindex只在赋值语句中产生效果,如:

>>>ser.reindex(['three','four','five','one'])

>>>print(ser)

one 2

two 5

three 7

four 4

>>>s=ser.reindex(['three','four','five','one'])

>>>print(s)

three 7.0

four 4.0

five NaN

one 2.0

类似地DataFrame:

>>>index=['Firefox','Chrome','Safari','Konqueror']

>>>df=pd.DataFrame({'http_status':[200,200,404,301],'response_time':[0.04,0.02,0.07,1.0]},index=index)

>>>print(df)

http_status response_time

Firefox 200 0.04

Chrome 200 0.02

Sarafi 404 0.07

Konqueror 301 1.00

>>>new_index=['Sarafi','Iceweasel','Comodo Dragon','Chrome']

#同样reindex结果不返回给df,在这里实时打印

>>>print(df.reindex(new_index))

http_status response_time

Sarafi 404 0.07

Icewasel NaN NaN

Comodo Dragon NaN NaN

Chrome 200 0.02

那么在写代码时谨记要在使用成员方法的同时给变量赋值就行了,或者将使用了成员方法的变量作为其它方法的输入型参数传递

>>>df = pd.DataFrame(np.arange(12).reshape(3, 4),

columns=['A', 'B', 'C', 'D'])

>>>print(df)

A B C D

0 0 1 2 3

1 4 5 6 7

2 8 9 10 11

>>>print(df.drop(['B','C'],axis=1))

A D

0 0 3

1 4 7

2 8 11

>>>arr=np.array([[2,3],[4,5]])

>>>combine=np.vstack((arr,df.drop(['B', 'C'], axis=1)))

>>>print(combine)

[[ 2 3]

[ 4 5]

[ 0 3]

[ 4 7]

[ 8 11]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值