python数据分析三:pandas的Series模块

 
 
# -*- coding: utf-8 -*-
import pandas as pd

from pandas import Series,DataFrame

import numpy as np
'''
Series 是一个简单的一维数组对象,带索引
'''
obj=Series([1,2,3,4])
print(obj)
# 0    1
# 1    2
# 2    3
# 3    4
# dtype: int64
#Series 特点左边索引又边值
print(obj.values)#[1 2 3 4]
print(obj.index)#RangeIndex(start=0, stop=4, step=1)

#自己标注索引
obj=Series([1,2,3,4],index=['a','b','c','d'])

print(obj)
# a    1
# b    2
# c    3
# d    4
# dtype: int64

print(obj.index)#Index(['a', 'b', 'c', 'd'], dtype='object')

#和字典一样,通过索引找值获取这数组
a=obj['a']
print(a)#1
#多值
b=obj[['a','b','c']]
print(b)
# a    1
# b    2
# c    3
# dtype: int64

'''
数组的运算索引值不会变
'''

print(obj[obj>2])
# c    3
# d    4
# dtype: int64
print(obj*2)
# a    2
# b    4
# c    6
# d    8
# dtype: int64
print(np.exp(obj))
# a     2.718282
# b
#      7.389056
# c    20.085537
# d    54.598150
# dtype: float64

#判断索引是否在数组中
print('a' in obj)#True
print('e' in obj)#False

#如果数组存放在python字典里,可以直接通过这个字典创建Series
dict={'hhb':24.3,'zjx':23.0,'zsb':88.0}
a=Series(dict)
print(a)
# hhb    24
# zjx    23
# zsb    88
# dtype: int64


#如果只传入一个字典
states=['hhb','zjx','ssb']
obj2=Series(dict,index=states)
print(obj2)
# hhb    24.0
# zjx    23.0
# ssb     NaN
# dtype: float64
#有索引的就会自动加载,没有的值不显示,多出来的索引,值为NaN,这就时所谓的缺失数据

print(obj2.isnull())
# hhb    False
# zjx    False
# ssb     True
# dtype: bool
pd.isnull(obj2)
pd.notnull(obj2)

#对于多数运算而言。Series算数运算会自动补齐不同的索引数据
print(obj2+a)
# hhb    48.6
# ssb     NaN
# zjx    46.0
# zsb     NaN
# dtype: float64



#Series本身有一个name属性
a.name='shit'
a.index.name='shit_name'
print(a)
# shit_name
# hhb    24.3
# zjx    23.0
# zsb    88.0
# Name: shit, dtype: float64

#Series索因可以通过赋值的方式,就改
a.index=['aaa','bbbb','ccc']
print(a)
# aaa     24.3
# bbbb    23.0
# ccc     88.0
# Name: shit, dtype: float64


猜你喜欢

转载自blog.csdn.net/qq_38788128/article/details/80625205