-1

I was trying to load the iris dataset using panda.

I did the fllowing:

import pandas as pd
iris= pd.read_csv("data_path/iris.csv")

However this is not in matrix form and I cannot access elements like iris[0][2].

I'm wondering how to transform the the csv file into a say numpy array?

AMC
  • 2,642
  • 7
  • 13
  • 35
small_angel
  • 81
  • 1
  • 4
  • Pandas reads data into it's own dataframe structure, but you can basically think of it as a dictionary, where column names are keys and values in said columns are, well... Values in an array. So, instead of converting it into a numpy 2D array you should consider using pandas's vast abilities to work with data and use Iris["column_name"][index] to get what you need – Karl Olufsen Apr 29 '20 at 03:21
  • 1
    Does this answer your question? [How do I read CSV data into a record array in NumPy?](https://stackoverflow.com/questions/3518778/how-do-i-read-csv-data-into-a-record-array-in-numpy) – wwii Apr 29 '20 at 03:35
  • I know for a fact there is plenty of information available which could help with this. What is particular about this question which isn't covered by those existing resources? Please see [ask], [help/on-topic]. – AMC Apr 29 '20 at 04:02

2 Answers2

0

If you insist on converting your dataframe into a numpy array, you can use iris.to_numpy() to get what you need, since pandas is built on top of numpy and they are tightly integrated. However, as I explained in my comment, you should consider investing some time into learning pandas, it is an incredibly powerful tool.

Karl Olufsen
  • 186
  • 1
  • 10
-2

There are two options to access the data:

First, use the pandas dataframe. To access rows, columns, or elements in a dataframe you can use .loc or .iloc.

import pandas as pd
iris= pd.read_csv("data_path/iris.csv")
iris.iloc[0,2]

You can learn more about it in this post:

PythonHow.com: Accessing Dataframe Columns Rows and Cells

Second, read the file using NumPy genfromtext function

import numpy as np
iris = np.genfromtxt("data_path/iris.csv")

Read this post to learn more:

RIP Tutorial: Reading CSV Files

ragad
  • 27
  • 3