目录

1 python 各类封装包数据类型

1.1 list类型

1.2 dict类型

1.3 tuple类型

1.4 array 数组对象

1.5 tensor 对象

1.6 DataFrame对象

2 python内数据类型之间转换

2.1 list, tuple转numpy

2.2 numpy 转 list

2.3 numpy 转 tensor

2.4 numpy 转 tensor

2.5 list 转 tensor

2.6 tensor转list

2.7 list 转 DataFrame


1 python 各类封装包数据类型

1.1 list类型

列表,是python中最基本的数据结构;

        1. 每个元素都可以通过索引获取,索引就是index = 0, 1, ...;

        2. 列表的数据项不需要有相同的数据类型,其写法就是: 使用逗号将不同的数据项分割,使用方括号扩起来就可以;

例子:

list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]

        3. 使用索引获取列表数据:

例子:

>>> list1 = ['physics', 'chemistry', 1997, 2000]
>>> list1[0]
'physics'
>>> list1[2:4]
[1997, 2000]

        4. 使用索引修改列表值:

例子:

>>> list1 = ['physics', 'chemistry', 1997, 2000]
>>> list1[3] = 2345
>>> list1
['physics', 'chemistry', 1997, 2345]

        5. 向列表添加元素:

例子:

>>> list1.append('qiqiqi')
>>> list1
['physics', 'chemistry', 1997, 2345, 'qiqiqi']

        6. 删除列表元素

例子:

>>> list1
['physics', 'chemistry', 1997, 2345, 'qiqiqi']
>>> del list1[1]
>>> list1
['physics', 1997, 2345, 'qiqiqi']


>>> list1.remove(1997)
>>> list1
['physics', 2345, 'qiqiqi']

        7. 合并两个列表

例子:

>>> list1
['physics', 1997, 2345, 'qiqiqi']
>>> list2 = [1,1,3]
>>> list1+list2
['physics', 1997, 2345, 'qiqiqi', 1, 1, 3]

        8. 获取某元素在列表中出现的次数

例子:

>>> list1+list2
['physics', 1997, 2345, 'qiqiqi', 1, 1, 3]
>>> (list1+list2).count(1)
2

        9. 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

例子:

>>> list1
['physics', 2345, 'qiqiqi']
>>> list1.extend(list2)
>>> list1
['physics', 2345, 'qiqiqi', 1, 1, 3]

1.2 dict类型

字典是python另一种可变容器模型,可以存储任意类型对象;

        字典的每个键值对( key:value )用冒号 : 分割,每个键值对之间用逗号 (, )分割,整个字典包括在花括号 {} 中;

        字典的键是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一;

        值可以取任意的数据类型;

        1. 通过键来访问值:

例子:

>>> tinydict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
>>> tinydict['Beth']
'9102'

        2. 使用键修改字典对应的值:
例子:

>>> tinydict['Beth'] = 6666
>>> tinydict
{'Alice': '2341', 'Beth': 6666, 'Cecil': '3258'}

        3. 删除某一元素, 清空字典,删除字典:

例子:

>>> del tinydict['Beth']
>>> tinydict
{'Alice': '2341', 'Cecil': '3258'}

>>> tinydict
{'Alice': '2341', 'Cecil': '3258'}
>>> tinydict.clear() # 清空字典
>>> tinydict
{}
>>> del tinydict # 删除字典
>>> tinydict
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'tinydict' is not defined

        4. 以列表返回一个字典所有的键

例子:

>>> tinydict.keys()
dict_keys(['Alice', 'Beth', 'Cecil'])

1.3 tuple类型

        与列表类型不同之处在于,其使用小括号,且值不能被修改;

                1. 使用索引访问元素(与list相同)

例子:

>>> tup1 = ('physics', 'chemistry', 1997, 2000)
>>> tup1[0]
'physics'

                2. 对元组进行连接:
例子:

>>> tup1 = ('physics', 'chemistry', 1997, 2000)
>>> tup1[0]
'physics'
>>> tup2 = ('1','cs')
>>> tup3 = tup1 + tup2
>>> tup3
('physics', 'chemistry', 1997, 2000, '1', 'cs')

1.4 array 数组对象

Numpy 支持大量的维度数组与矩阵运算,且针对数组运算提供了大量的数学函数库;

        NumPy 通常与 SciPy(Scientific Python, SciPy 是一个开源的 Python 算法库和数学工具包)和 Matplotlib(绘图库,是 Python 编程语言及其数值数学扩展包 NumPy 的可视化操作界面)一起使用, 这种组合广泛用于替代 MatLab,是一个强大的科学计算环境,有助于我们通过 Python 学习数据科学或者机器学习;

        1. NumPy 最重要的一个特点是其 N 维数组对象 ndarray,它是一系列同类型数据的集合

        2. ndarray 是用于存放同类型元素的多维数组,每个元素占有相同大小的内存区域;

        3. 创建n维数组;

例子:

>>> import numpy as np
>>> a = np.array([1,2,3])  # 一维数组
>>> a
array([1, 2, 3])
>>> a = np.array([[1,  2],  [3,  4]])
>>> a
array([[1, 2],
       [3, 4]]) # 多维数组

        4. numpy.empty 方法用来创建一个指定形状(shape)、数据类型(dtype)且未赋值的数组

例子:

>>> x = np.empty([3,2], dtype = int)
>>> x
array([[ 7290888465049002104,  3184989590875566189],
       [ 8104636977815248178,  2987133850644979813],
       [-5764607523034234870, -5764607523034234880]])
>>> x.shape
(3, 2)
>>> x.dtype
dtype('int64')

        5. 创建值全为0的数组:

例子:

>>> x = np.zeros(5) # 默认是浮点数类型
>>> x
array([0., 0., 0., 0., 0.])
>>> y = np.zeros((5,), dtype = int) 
>>> y
array([0, 0, 0, 0, 0])
>>> y.shape
(5,)
>>> y.dtype
dtype('int64')
>>> n = np.zeros((3,2))
>>> n
array([[0., 0.],
       [0., 0.],
       [0., 0.]])

        6.  从数值范围创建数组(np.arange):

例子:

numpy.arange(start, stop, step, dtype)
# start 起始值,默认为0
# stop 终止值(不包含)
# step 步长,默认为1
# dtype 返回ndarray的数据类型,如果没有提供,则会使用输入数据的类型

>>> x = np.arange(1,5,2) 
>>> x
array([1, 3])

        7. 修改数组形状:

例子:

numpy.reshape(arr, newshape, order='C') # 不改变数据的条件下修改形状
# arr:要修改形状的数组
# newshape:整数或者整数数组,新的形状应当兼容原有形状

>>> a = np.arange(8)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> b = a.reshape(4,2)
>>> b
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
ndarray.flatten(order='C') # 返回一份数组拷贝,对拷贝所做的修改不会影响原始数组
# order:'C' -- 按行,'F' -- 按列,'A' -- 原顺序,'K' -- 元素在内存中的出现顺序。

>>> b.flatten(order = 'F')
array([0, 2, 4, 6, 1, 3, 5, 7])

1.5 tensor 对象

        torch.Tensor是一种包含单一数据类型元素的多维矩阵;torch.Tensor是默认的tensor类型(torch.FlaotTensor)的简称;

                1. 张量可以从python的list构成;

例子:

>>> import torch
>>> a = torch.FloatTensor([[1, 2, 3], [4, 5, 6]])
>>> a
tensor([[1., 2., 3.],
        [4., 5., 6.]])

                2. 创建未初始化的张量

例子:

>>> x = torch.empty(5,3)
>>> x
tensor([[0.0000e+00, 1.4013e-45, 0.0000e+00],
        [0.0000e+00, 0.0000e+00, 0.0000e+00],
        [0.0000e+00, 0.0000e+00, 0.0000e+00],
        [1.1704e-41, 0.0000e+00, 2.2369e+08],
        [0.0000e+00, 0.0000e+00, 0.0000e+00]])

                3. 创建随机初始化的张量:

例子:

>>> y = torch.rand(2,2) # 包含了从区间[0,1)的均匀分布中抽取一组随机数,形状由可变参数size定义
>>> y
tensor([[0.7967, 0.0257],
        [0.0560, 0.9289]])
>>> y.size
<built-in method size of Tensor object at 0x7fa945882e50>
>>> y.size()
torch.Size([2, 2])
>>> y.shape
torch.Size([2, 2])

                4. 创建全为0的张量

例子:

>>> z = torch.zeros(2,2)
>>> z
tensor([[0., 0.],
        [0., 0.]])

                5. 随机生成张量

例子:

>>> q = torch.arange(8)
>>> q
tensor([0, 1, 2, 3, 4, 5, 6, 7])

                6. 张量数据类型转换:

例子:

# 使用独立的函数如 int(),float()等进行转换
>>> q = q.float()
>>> q
tensor([0., 1., 2., 3., 4., 5., 6., 7.])

# 使用torch.type()函数
>>> q = q.type(torch.FloatTensor)
>>> q
tensor([0., 1., 2., 3., 4., 5., 6., 7.])

# 使用type_as()函数
>>> y = torch.arange(2)
>>> y = y.type_as(q)
>>> y
tensor([0., 1.])

                7. 张量形状改变

例子:

>>> q.view(4,-1)
tensor([[0., 1.],
        [2., 3.],
        [4., 5.],
        [6., 7.]])

                8. 张量压缩维度:

例子:

>>> q = q.view(4,1,-1)
>>> q.shape
torch.Size([4, 1, 2])
>>> q = q.squeeze(1)
>>> q
tensor([[0., 1.],
        [2., 3.],
        [4., 5.],
        [6., 7.]])
>>> q.shape
torch.Size([4, 2])

                9. 张量扩张维度

例子:

>>> q = q.unsqueeze(1)
>>> q.shape
torch.Size([4, 1, 2])

1.6 DataFrame对象

DataFrame 是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔型值)。

        DataFrame既有行索引,也有列索引,可以看作由 Series 组成的字典(共同用一个索引);

        1. DataFrame构造方法

例子:

pandas.DataFrame( data, index, columns, dtype, copy)
# data:一组数据(ndarray、series, map, lists, dict 等类型)
# index:索引值,或者可以称为行标签
# columns:列标签,默认为 RangeIndex (0, 1, 2, …, n) 
# dtype:数据类型
>>> import pandas as pd
>>> data = [['Google',10],['Runoob',12],['Wiki',13]]
>>> df = pd.DataFrame(data,columns=['Site','Age'],dtype=float)
>>> df
     Site   Age
0  Google  10.0
1  Runoob  12.0
2    Wiki  13.0

        2. 使用 nparray (ndarray 的长度必须相同)创建DataFrame

例子:

>>> data = {'Site':['Google', 'Runoob', 'Wiki'], 'Age':[10, 12, 13]}
>>> data
{'Site': ['Google', 'Runoob', 'Wiki'], 'Age': [10, 12, 13]}
>>> type(data)
<class 'dict'>
>>> data = pd.DataFrame(data)
>>> data
     Site  Age
0  Google   10
1  Runoob   12
2    Wiki   13

         3. 使用dict创建DataFrame,没有对应的部分数据为 NaN

例子:

>>> data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
>>> df = pd.DataFrame(data)
>>> df
   a   b     c
0  1   2   NaN
1  5  10  20.0

         4. 使用 loc 属性返回指定行的数据,如果没有设置索引,第一行索引为 0,第二行索引为 1

例子:

>>> df
   a   b     c
0  1   2   NaN
1  5  10  20.0
>>> df.loc[0]
a    1.0
b    2.0
c    NaN
Name: 0, dtype: float64

        5. 返回指定列的数据

例子:

>>> df['a']
0    1
1    5
Name: a, dtype: int64

2 python内数据类型之间转换

2.1 list, tuple转numpy

使用: numpy = np.array(list)

例子:

>>> list1
['physics', 2345, 'qiqiqi', 1, 1, 3]
>>> numpy1 = np.array(list1)
>>> numpy1
array(['physics', '2345', 'qiqiqi', '1', '1', '3'], dtype='<U21')

>>> tup1 = (1,3,'ds')
>>> numpy3 = np.array(tup1)
>>> numpy3
array(['1', '3', 'ds'], dtype='<U21') # 可以看到元素是同一数据类型
# 这个array不能转化为tensor类型,因为 tensor内元素不支持string类型

2.2 numpy 转 list

使用: list = numpy.tolist()

例子:

>>> numpy2 = np.arange(4)
>>> numpy2
array([0, 1, 2, 3])
>>> list2 = numpy2.tolist()
>>> list2
[0, 1, 2, 3]

2.3 numpy 转 tensor

使用: tensor = torch.tensor(numpy ) 或者 tensor = torch.from_numpy(numpy)

例子:

>>> numpy4 = np.empty((3,2))
>>> numpy4
array([[0., 0.],
       [0., 0.],
       [0., 0.]])
>>> tensor1 = torch.tensor(numpy4)
>>> tensor1
tensor([[0., 0.],
        [0., 0.],
        [0., 0.]], dtype=torch.float64)

# from_numpy形式
>>> numpy5 = np.arange(4)
>>> numpy5
array([0, 1, 2, 3])
>>> tensor2 = torch.from_numpy(numpy5)
>>> tensor2
tensor([0, 1, 2, 3])

2.4 numpy 转 tensor

使用: numpy = tensor.numpy() 或者 numpy = tensor.detach().numpy()

        主要区别在于是否使用detach(),也就是返回的新变量是否需要计算梯度。【用了detach(),不需要计算梯度了】

例子:

>>> numpy6 = tensor2.numpy()
>>> numpy6
array([0, 1, 2, 3])


>>> numpy7 = tensor2.detach().numpy()
>>> numpy7
array([0, 1, 2, 3])

2.5 list 转 tensor

        先转为numpy, 再转为tensor,包装list内的元素是tensor内元素要求的类型(float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.) 且list内元素维度一致;

例子:

        当list内元素包含list,和其他类型时,不能转化:

>>> list3 = [1,2,[2,3]]
>>> numpy8 = np.array(list3)
array([1, 2, list([2, 3])], dtype=object)
>>> tensor4 = torch.tensor(numpy8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.
 # 因为numpy中元素是list类型的

        正常情况:

>>> list4 = [[1,2],[2,3]]
>>> numpy9 = np.array(list4)
>>> numpy9
array([[1, 2],
       [2, 3]])
>>> tensor5 = torch.tensor(numpy9)
>>> tensor5
tensor([[1, 2],
        [2, 3]])

        list转tensor 也可以直接转化

例子:

>>> tensor6 = torch.tensor(list4)
>>> tensor6
tensor([[1, 2],
        [2, 3]])

        当list中的每个元素都是tensor类型时:

转化方法:

val = torch.tensor([item.cpu().detach().numpy() for item in val]).cuda()

2.6 tensor转list

Tensor不可直接转换为list , 需要先转换为numpy,然后在转换为list

        使用: list = tensor.numpy().tolist()

例子:

>>> list5 = tensor6.numpy().tolist()
>>> list5
[[1, 2], [2, 3]]

2.7 list 转 DataFrame

两个不同列表转换成为DataFrame:

使用: DataFrame = pd.DataFrame(list)

例子:

>>> a=[1,2,3,4]#列表a
>>> b=[5,6,7,8]#列表b
>>> c={"a" : a,"b":b}
>>> data = pd.DataFrame(c)
>>> data
   a  b
0  1  5
1  2  6
2  3  7
3  4  8

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐