【问题标题】:Convert an ndArray of set to a matrix将集合的 ndArray 转换为矩阵
【发布时间】:2018-09-27 09:24:06
【问题描述】:

我有一个从文件加载的数据集 -

np.array([(5.1, 3.5, 1.4, 0.2, 'Iris-setosa'),
          (4.9, 3., 1.4, 0.2, 'Iris-setosa'),
          (4.7, 3.2, 1.3, 0.2, 'Iris-setosa'),
          (4.6, 3.1, 1.5, 0.2, 'Iris-setosa'),
          (5., 3.6, 1.4, 0.2, 'Iris-setosa')])

如何获得前 4 列的矩阵 -

np.array([[5.1, 3.5, 1.4, 0.2],
          [4.9, 3., 1.4, 0.2],
          [4.7, 3.2, 1.3, 0.2],
          [4.6, 3.1, 1.5, 0.2],
          [5., 3.6, 1.4, 0.2]])

并将标签放入另一个数组-

np.array(['Iris-setosa', 'Iris-setosa', 'Iris-setosa', 'Iris-setosa',
          'Iris-setosa'])

【问题讨论】:

  • 您的输入不是有效的 Python。请提供正确的输入定义。
  • 这个数组的dtype 是什么?对于(),我猜它是一个结构化数组,可能由genfromtxt 生成。如果是这样,字符串 'column' 很容易通过名称访问,arr['f4']

标签: python numpy


【解决方案1】:
import pandas as pd

data=np.array([(5.1, 3.5, 1.4, 0.2, 'Iris-setosa') ,
 (4.9, 3. , 1.4, 0.2, 'Iris-setosa'),
 (4.7, 3.2, 1.3, 0.2, 'Iris-setosa'),
 (4.6, 3.1, 1.5, 0.2, 'Iris-setosa'),
 (5. , 3.6, 1.4, 0.2, 'Iris-setosa')])

df= pd.DataFrame(data)
first4col = df.iloc[:,0:3]
tags=df.iloc[:,4]

【讨论】:

    猜你喜欢
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多