Home > Blockchain >  First Time Importing CSV into Python
First Time Importing CSV into Python

Time:11-21

I am an R user and have recently been learning how to use Python!

In R, I normally import CSV files like this:

> getwd()
[1] "C:/Users/me/OneDrive/Documents"

my_file = read.csv("my_file.csv")

Now, I am trying to learn how to do this in Python.

I first tried this code and got the following error:

import pandas as pd

df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv')

File "<ipython-input-17-45a11fa3e8b1>", line 1
    df = pandas.read_csv('C:\Users\me\OneDrive\Documents\my_file.csv')
                         ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I then tried this alternate method, but still got an error:

df = pandas.read_csv(r"C:\Users\me\OneDrive\Documents\my_file.csv")

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-20-c0ac0d536b37> in <module>
----> 1 df = pandas.read_csv(r"C:\Users\me\OneDrive\Documents\my_file.csv")

NameError: name 'pandas' is not defined

Can someone please show me what I am doing wrong and how to fix this?

Thank you!

Note: I am using Jupyter Notebooks within Anaconda

CodePudding user response:

Regarding the second error, make sure pandas module is installed in your system. You can run this code snippet in the terminal to install the module.

pip install pandas -U

In python \somealphabet is represented as a Unicode character. What you can do is, you can either use \\somealphabet or replace \ with /

df = pd.read_csv('C:\\Users\\me\\OneDrive\\Documents\\my_file.csv')

df = pd.read_csv('C:/Users/me/OneDrive/Documents/my_file.csv')

CodePudding user response:

df = pd.read_csv(r'C:/Users/me/OneDrive/Documents/my_file.csv',  encoding='latin-1')

I fixed my own problem!

  • Related