简体   繁体   中英

Cannot Import Data in Python Using Pandas

I am working through the following machine learning tutorial:

http://machinelearningmastery.com/machine-learning-in-python-step-by-step/

Here is my (mac) development environment:

Python 2.7.10 
scipy: 0.13.0b1
numpy: 1.8.0rc1
matplotlib: 1.3.1
pandas: 0.20.2
sklearn: 0.18.1

When I try to run a script, to load the data from a URL containing the CSV data, I get the following error:

Traceback (most recent call last):
  File "load_data.py", line 4, in <module>
    dataset = pandas.read_csv(url, names=names)
NameError: name 'pandas' is not defined

Here's the script:

# Load dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = pandas.read_csv(url, names=names)

your error says:

    dataset = pandas.read_csv(url, names=names)
NameError: name 'pandas' is not defined

which means you're trying to use pandas.read_csv() without importing Pandas first. when you want to use an external library, you have to import it. if it's not installed on your machine, you may have to install it first too. assuming pandas is installed on your machine, this code will work:

import pandas
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = pandas.read_csv(url, names=names)

output:

dataset.head(3)

   sepal-length  sepal-width  petal-length  petal-width        class
0           5.1          3.5           1.4          0.2  Iris-setosa
1           4.9          3.0           1.4          0.2  Iris-setosa
2           4.7          3.2           1.3          0.2  Iris-setosa

You can download the data first before importing it

import urllib
import pandas as pd

file_path = "./iris.csv"

#download data
urllib.request.urlretrieve("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", file_path)

#load it
dataset = pd.read_csv(file_path, names=names)

Hope it helps

You are getting that error because "pandas" is not yet imported. pandas is an import library for python.

Fix: import pandas

You can use it after that.

Better Alternative: import pandas as pd

=> 'pd' will be a short-form representative for pandas in your script. It is advisable to import this way to reduce you having to retype "pandas" every-time you need to write it in code.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM