series和DataFrame

发布时间 2023-10-26 22:51:55作者: YaYa000

Series

Series是一个类似于一维数组的对象,它能够保存所有类型的数据。

class pandas.Series(data=None,index=None,dtype=None,name=None,copy=False,fastpath=False)

name是指Series对象的名字

copy是指是否对数据进行复制

fastpath是指校验Series的对象名称

import pandas as pd
# 创建对象,并指定索引
data = pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
print(data)
# 用字典形式创建对象
data_1 = pd.Series({'a':1,'b':2,'c':3,'d':4,'e':5})
print(data_1)
# 获取索引
print(data_1.index)
# 获取值
print(data_1.values)
# 按位置进行索引
print(data_1[3])
# 对数据进行运算
data_1*2
​
​
# -----------------------------下面是输出结果-------------------------------
a    1
b    2
c    3
d    4
e    5
dtype: int64
-----------------------------------------------------------------
a    1
b    2
c    3
d    4
e    5
dtype: int64
------------------------------------------------------------------
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
------------------------------------------------------------------
[1 2 3 4 5]
------------------------------------------------------------------
4
------------------------------------------------------------------
a     2
b     4
c     6
d     8
e    10
dtype: int64

 

 

DataFrame

DataFrame 是一个类似于二维数组或者表格的对象,它的每列数据可以是不同的数据类型

# DataFrame
import numpy as np
import pandas as pd
# 创建一个数组
arr = np.array([[1,2,3,4],[4,5,6,7]])
# 将数组转换为DataFrame形式,并指定索引列
arr_1 = pd.DataFrame(arr,columns=['No1','No2','No3','No4'])
print(arr_1)
# 通过索引的方式获取一列数据
print(arr_1['No3'])
# 查看索引的数据的类型
print(type(arr_1['No3']))
# 列索引也可以用下面这种方式
print(arr_1.No3)
# 查看数据类型
print(type(arr_1.No3))
# 给DataFrame增加数据
arr_1['No4']=[8,4]
print(arr_1)
# 删除No3这一列数据
del arr_1['No3']
arr_1
​
​
# -----------------------------------下面是输出结果------------------------------------
   No1  No2  No3  No4
0    1    2    3    4
1    4    5    6    7
--------------------------------------------------
0    3
1    6
Name: No3, dtype: int32
--------------------------------------------------
<class 'pandas.core.series.Series'>
--------------------------------------------------
0    3
1    6
Name: No3, dtype: int32
--------------------------------------------------
<class 'pandas.core.series.Series'>
--------------------------------------------------
   No1  No2  No3  No4
0    1    2    3    8
1    4    5    6    4
--------------------------------------------------
No1 No2 No4
0   1   2   8
1   4   5   4