【pandas】1.创建Series对象

目录

1.使用列表创建Series对象

 2.使用字典创建Series对象

 3.创建索引号为日期的Series对象

import pandas as pd
import numpy as np
#numpy的引用不是必须的,只是为了举例

1.使用列表创建Series对象

a=pd.Series([4,5,6],range(1,4),dtype=numpy.int32,name='aa')
#dtype默认为int64,可以使用numpy修改
print(a)
>>> 1    4
    2    5
    3    6
    Name: aa, dtype: int64

b=pd.Series([1,'x',3.4,np.nan,[1,2]],range(1,6))
print(b)
>>> 1         1
    2         x
    3       3.4
    4       NaN
    5    [1, 2]
    dtype: object

 Series对象中的元素可以同为一种类型(如a),也可以各不相同(如b)

当元素类型不相同时,dtype=object

print('所有元素值:',b.values)
>>> 所有元素值: [1 'x' 3.4 nan list([1, 2])] #<class 'numpy.ndarray'>

print('所有索引号:',b.keys())
>>> 所有索引号: RangeIndex(start=1, stop=6, step=1) 

print('所有索引名明细:',*b.index)
>>> 所有索引名明细: 1 2 3 4 5

print('所有键值对明细:',*b.items()) 
>>> 所有键值对明细: (1, 1) (2, 'x') (3, 3.4) (4, nan) (5, [1, 2])

b.values  #得到序列的元素组成的数组

b.keys() #得到索引号

b.index #得到索引名

*b.items() #得到每个键值对

加上*得到明细,如:

*b.keys()=1 2 3 4 5

 2.使用字典创建Series对象

pd.set_option('display.unicode.east_asian_width',True)#使打印结果正确对齐
d=pd.Series({'考号':'10182156','姓名':'王小丫','科目一':'97'})
print(d)
>>> 考号      10182156
    姓名        王小丫
    科目一          97
    dtype: object

print(d.values)
>>> ['10182156' '王小丫' '97']
print(*d.index)
>>> 考号 姓名 科目一

pd.set_option('display.unicode.east_asian_width',True) #使打印结果对齐

 3.创建索引号为日期的Series对象

dates=pd.date_range('20210315','20210318')
print(dates)
>>> DatetimeIndex(['2021-03-15', '2021-03-16', '2021-03-17', '2021-03-18'], dtype='datetime64[ns]', freq='D')

c=pd.Series([6,7,8,9],index=dates)
print(c)
>>> 2021-03-15    6                                        
    2021-03-16    7
    2021-03-17    8
    2021-03-18    9
    Freq: D, dtype: int64

print(*c.keys())#不只天还有时间(时、分、秒)
>>> 2021-03-15 00:00:00 2021-03-16 00:00:00 2021-03-17 00:00:00 2021-03-18 00:00:00

猜你喜欢

转载自blog.csdn.net/xucanlax/article/details/123980593