python中如何提取一组数据中的第一列数据
概述
直接提取会报错,把array数组转换成list,即可提取,使用numpy转换
步骤详解
1、直接提取尝试:
group=[[1,2],[2,3],[3,4]]
#提取第一列元素
print(group[:,1])
#Out:TypeError: list indices must be integers or slices, not tuple
2、使用numpy转换:
import numpy as np
group=[[1,2],[2,3],[3,4]]
#numpy转化
ar=np.array(group)
print(ar[:,1])
#Out:[2 3 4]
拓展内容
numpy详解
Numpy对象是数组,称为ndarray
维度(dimensions)称作轴(axes),轴的个数叫做秩(rank)。注:有几级中括号就有几个维度
一、ndarray.attrs:
ndarray.ndim 秩
ndarray.shape 例如一个2排3列的矩阵,它的shape属性是(2,3)
ndarray.size 数组元素的总个数
ndarray.dtype 元素类型,NumPy提供自己的数据类型
ndarray.itemsize 数组中每个元素的字节大小
二、数组创建函数:
array
asarray将输入转换成ndarray
arange
ones
zeros
empty 只分配内存空间不填充任何值
eye 创建N*N单位矩阵(对角线为1)
三、数组和标量之间的运算
numpy数组的一个特点,不用编写循环就可对数据执行批量运算,这通常称作矢量化(vectorization)。
四、基本的索引和切片
numpy数组的索引是一个内容丰富的主题,因为选取数据子集或单个元素的方式有很多。这里我仅详细介绍常用的方法,对于高级功能的方式我列举名称,读者可以等到要用的时候自行查阅资料。
>>> arr
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
[14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
[16, 17, 18, 19, 20, 21, 22, 23, 24, 25],
[17, 18, 19, 20, 21, 22, 23, 24, 25, 26],
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27],
[19, 20, 21, 22, 23, 24, 25, 26, 27, 28],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]]
>>> l = [x[0] for x in arr]
>>> l
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
>>>
2017-07-13
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
[14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
[16, 17, 18, 19, 20, 21, 22, 23, 24, 25],
[17, 18, 19, 20, 21, 22, 23, 24, 25, 26],
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27],
[19, 20, 21, 22, 23, 24, 25, 26, 27, 28],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]])
>>> l = arr.T[0]
>>> l
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21])
用split