Pandas——常用数据结构Series

pandas是创建在numpy之上的,在导入库的时候,平常都是同时导入这两个库
下面的程序都默认先导入和这两个库

Pandas的两种常用数据结构

Series和DataFrame

DataFrame数据结构

是pandas的基本数据,类似于excel表格形式的数据
它既有行索引又有列索引

Series数据结构

一组数据和一组对应的数据标签(索引)组成
可看成dataframe中的一列

series数据创建

使用pandas.Series(data,index,dtype,name)
data:可以是列表,数组或字典(np.array())
index:索引,必须与数据同长度,
name:对象的名称

a=pd.Series([1,2,3,4,5],index=[1,'中国','c','d','e'],name='自己')
b=pd.Series([1,2,3,4,5])
print(a);print('*'*10);print(b)
'''
1    1
中国    2
c    3
d    4
e    5
Name: 自己, dtype: int64
**********
0    1
1    2
2    3
3    4
4    5
dtype: int64
'''

从上面的运行来看,知道默认索引为0开始的值,自定义nameindex可以是任何类型的值

series的常用属性

values: 返回series对象的索引元素
index:返回索引
dtype:返回数据类型
shape:返回series数据形状
ndim:返回对象维度
size: 返回对象个数

a=pd.Series([1,2,34,4,5],\
	index=[1,'中国','c','d','e'],\
	name='自己',dtype=int)
print(a.values);print(a.index)
print(a.shape);print(a.ndim)
print(a.size)
'''
[ 1  2 34  4  5]
Index([1, '中国', 'c', 'd', 'e'], dtype='object')
(5,)
1
5
'''
series的切片访问

切片中括号内可以是整型切片数值,也可以是对象本身的索引,只是本身切片包含最后的索引项

a=pd.Series([1,2,34,4,5],index=['a','b','c','d','e'],name='自己',dtype=int)
print(a[0:3]);print('*'*20);print(a['a':'d'])
'''
a     1
b     2
c    34
Name: 自己, dtype: int32
********************
a     1
b     2
c    34
d     4
Name: 自己, dtype: int32
'''
series的方法
连接两个对象,对象1.append(对象2)

series_obj1.append(series_obj2)

a=pd.Series({'北京':8,'广东':9,'上海':12,'重庆':6})
b=pd.Series({'深圳':20,'珠海':60,})
print(a);print('*'*15);print(b);print('*'*15)
print(a.append(b))
'''
北京     8
广东     9
上海    12
重庆     6
dtype: int64
***************
深圳    20
珠海    60
dtype: int64
***************
北京     8
广东     9
上海    12
重庆     6
深圳    20
珠海    60
dtype: int64
'''
series对象内容的修改和删除

注意,使用series_obj.drop(‘key_value’,inplace=ture)才能删除原来对象内容,

a=pd.Series({'北京':8,'广东':9,'上海':12,\
			'重庆':6})
# b=pd.Series({'深圳':20,'珠海':60,})
a['北京']=99
print(a);print('*'*10);print(a.drop('北京'))
print('?'*10);print(a);print('!'*10);
a.drop('北京',inplace=True);print(a)
'''
北京    99
广东     9
上海    12
重庆     6
dtype: int64
***************
广东     9
上海    12
重庆     6
dtype: int64
??????????
北京    99
广东     9
上海    12
重庆     6
dtype: int64
!!!!!!!!!!
广东     9
上海    12
重庆     6
dtype: int64
'''
发布了70 篇原创文章 · 获赞 1 · 访问量 2437

猜你喜欢

转载自blog.csdn.net/weixin_43794311/article/details/104587678
今日推荐