如何在Google Colab中将csv读取到dataframe [英] How to read csv to dataframe in Google Colab

查看:1037
本文介绍了如何在Google Colab中将csv读取到dataframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取本地存储在计算机上的csv文件. (仅供参考,它是来自Kaggle的钛酸数据,此处.)

来自问题和答案我了解到您可以使用此代码导入数据对我来说效果很好.

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

我迷路的地方是如何从此处将其转换为数据框. 示例Google笔记本页面在上面的答案中列出了不谈论它.

我正在尝试使用from_dict命令将字典uploaded转换为数据帧,但无法使其工作.在此处中,有一些关于将dict转换为数据帧的讨论,但解决方案不适用对我(我认为).

总而言之,我的问题是:

如何将本地存储在文件中的csv文件转换为熊猫 Google合作实验室的数据框?

解决方案

熊猫read_csv应该可以解决问题.您需要将上传的字节包装在io.StringIO中,因为read_csv需要一个类似文件的对象.

这是一个完整的例子: https://colab.research.google.com/notebook#fileId=1JmwtF5OmSghC -y3-BkvxLan0zYXqCJJf

关键代码段是:

import pandas as pd
import io

df = pd.read_csv(io.StringIO(uploaded['train.csv'].decode('utf-8')))
df

I am trying to read a csv file which I stored locally on my machine. (Just for additional reference it is titanic data from Kaggle which is here.)

From this question and answers I learnt that you can import data using this code which works well from me.

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

Where I am lost is how to convert it to dataframe from here. The sample google notebook page listed in the answer above does not talk about it.

I am trying to convert the dictionary uploaded to dataframe using from_dict command but not able to make it work. There is some discussion on converting dict to dataframe here but the solutions are not applicable to me (I think).

So summarizing, my question is:

How do I convert a csv file stored locally on my files to pandas dataframe on Google Colaboratory?

解决方案

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 pd
import io

df = pd.read_csv(io.StringIO(uploaded['train.csv'].decode('utf-8')))
df

这篇关于如何在Google Colab中将csv读取到dataframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆