How to read csv to dataframe in Google Colab How to read csv to dataframe in Google Colab python python

How to read csv to dataframe in Google Colab


step 1- Mount your Google Drive to Collaboratory

from google.colab import drive drive.mount('/content/gdrive')

step 2- Now you will see your Google Drive files in the left pane (file explorer). Right click on the file that you need to import and select çopy path. Then import as usual in pandas, using this copied path.

import pandas as pd df=pd.read_csv('gdrive/My Drive/data.csv')

Done!


Pandas read_csv should do the trick. You'll want to wrap your uploaded bytes in an io.StringIO since read_csv expects a file-like object.

Here's a full example:https://colab.research.google.com/notebook#fileId=1JmwtF5OmSghC-y3-BkvxLan0zYXqCJJf

The key snippet is:

import pandas as pdimport iodf = pd.read_csv(io.StringIO(uploaded['train.csv'].decode('utf-8')))df


Colab google: uploading csv from your PCI had the same problem with an excel file (*.xlsx), I solved the problem as the following and I think you could do the same with csv files:- If you have a file in your PC drive called (file.xlsx) then:1- Upload it from your hard drive by using this simple code:

from google.colab import filesuploaded = files.upload()

Press on (Choose Files) and upload it to your google drive.

2- Then:

import iodata = io.BytesIO(uploaded['file.XLSX'])    

3- Finally, read your file:

import pandas as pd   f = pd.read_excel(data , sheet_name = '1min', header = 0, skiprows = 2)#df.sheet_namesdf.head()

4- Please, change parameters values to read your own file. I think this could be generalized to read other types of files!
Enjoy it!