将Google电子表格CSV放入Pandas Dataframe

时间:2013-10-26 20:46:52

标签: python pandas google-sheets google-drive-api google-apps

我上传了一个文件到Google电子表格(制作一个公开可访问的示例IPython Notebook,带有数据)我正在使用该文件的原生形式可以读入Pandas Dataframe。所以现在我使用以下代码来阅读电子表格,工作正常,但只是以字符串形式出现,我没有运气试图将其恢复到数据框中(您可以获取数据)

import requests
r = requests.get('https://docs.google.com/spreadsheet/ccc?key=0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc&output=csv')
data = r.content

数据最终看起来像:(第1行标题)

',City,region,Res_Comm,mkt_type,Quradate,National_exp,Alabama_exp,Sales_exp,Inventory_exp,Price_exp,Credit_exp\n0,Dothan,South_Central-Montgomery-Auburn-Wiregrass-Dothan,Residential,Rural,1/15/2010,2,2,3,2,3,3\n10,Foley,South_Mobile-Baldwin,Residential,Suburban_Urban,1/15/2010,4,4,4,4,4,3\n12,Birmingham,North_Central-Birmingham-Tuscaloosa-Anniston,Commercial,Suburban_Urban,1/15/2010,2,2,3,2,2,3\n

引入磁盘驻留文件的本机pandas代码如下所示:

df = pd.io.parsers.read_csv('/home/tom/Dropbox/Projects/annonallanswerswithmaster1012013.csv',index_col=0,parse_dates=['Quradate'])

“干净”的解决方案对许多人来说很有帮助,可以提供一种简单的方法来共享数据集供熊猫使用!我尝试了一堆替代方案但没有成功,我很确定我再次错过了一些明显的东西。

只是一个更新说明新的Google电子表格有不同的网址格式只是在上面的示例和/或下面的答案中使用它来代替URL,你应该没问题就是一个例子:

https://docs.google.com/spreadsheets/d/177_dFZ0i-duGxLiyg6tnwNDKruAYE-_Dd8vAQziipJQ/export?format=csv&id

请参阅下面的@Max Ghenis解决方案,它只使用了pd.read_csv,不需要StringIO或请求......

7 个答案:

答案 0 :(得分:49)

您可以在read_csv()对象上使用StringIO

from io import BytesIO

import requests
r = requests.get('https://docs.google.com/spreadsheet/ccc?key=0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc&output=csv')
data = r.content

In [10]: df = pd.read_csv(BytesIO(data), index_col=0,parse_dates=['Quradate'])

In [11]: df.head()
Out[11]: 
          City                                            region     Res_Comm  \
0       Dothan  South_Central-Montgomery-Auburn-Wiregrass-Dothan  Residential   
10       Foley                              South_Mobile-Baldwin  Residential   
12  Birmingham      North_Central-Birmingham-Tuscaloosa-Anniston   Commercial   
38       Brent      North_Central-Birmingham-Tuscaloosa-Anniston  Residential   
44      Athens                 North_Huntsville-Decatur-Florence  Residential   

          mkt_type            Quradate  National_exp  Alabama_exp  Sales_exp  \
0            Rural 2010-01-15 00:00:00             2            2          3   
10  Suburban_Urban 2010-01-15 00:00:00             4            4          4   
12  Suburban_Urban 2010-01-15 00:00:00             2            2          3   
38           Rural 2010-01-15 00:00:00             3            3          3   
44  Suburban_Urban 2010-01-15 00:00:00             4            5          4   

    Inventory_exp  Price_exp  Credit_exp  
0               2          3           3  
10              4          4           3  
12              2          2           3  
38              3          3           2  
44              4          4           4  

答案 1 :(得分:46)

似乎在没有StringIO的情况下为我工作:

test = pd.read_csv('https://docs.google.com/spreadsheets/d/' + 
                   '0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc' +
                   '/export?gid=0&format=csv',
                   # Set first column as rownames in data frame
                   index_col=0,
                   # Parse column values to datetime
                   parse_dates=['Quradate']
                  )
test.head(5)  # Same result as @TomAugspurger

BTW,包括导致不同工作表的?gid=,可以在网址中找到gid。

答案 2 :(得分:8)

我的方法有点不同。我只是使用pandas.Dataframe()但显然需要安装和导入gspread。它工作得很好!

gsheet = gs.open("Name")
Sheet_name ="today"
wsheet = gsheet.worksheet(Sheet_name)
dataframe = pd.DataFrame(wsheet.get_all_records())

答案 3 :(得分:7)

在浏览器中打开所需的特定工作表。确保拥有该链接的任何人至少可以查看它。复制并粘贴网址。你会得到https://docs.google.com/spreadsheets/d/BLAHBLAHBLAH/edit#gid=NUMBER之类的东西。

sheet_url = 'https://docs.google.com/spreadsheets/d/BLAHBLAHBLAH/edit#gid=NUMBER'

首先我们将其转换为CSV导出网址,例如https://docs.google.com/spreadsheets/d/BLAHBLAHBLAH/export?format=csv&gid=NUMBER

csv_export_url = sheet_url.replace('/edit#gid=', '/export?format=csv&gid=')

然后我们将其传递给pd.read_csv,后者可以使用网址。

df = pd.read_csv(csv_export_url)

如果Google更改其API(似乎没有记录),这将会中断,并且如果发生网络故障,可能会给出无用的错误。

答案 4 :(得分:3)

我一直在使用以下工具,到目前为止一直有效:

https://docs.google.com/spreadsheets/d/{key}/edit/

您必须指定sheet_name和密钥。关键是您从以下路径中的网址获取的字符串:this.props.navigation.navigate('ScreenOneRoute', {name: data.name});

如果列名有多行,则可以更改标题的值,但我不确定它是否仍适用于多标题。

如果谷歌改变他们的API,它可能会制造。

另请注意,您的电子表格必须是公开的,有链接的每个人都可以阅读。

答案 5 :(得分:3)

如果csv文件是通过驱动器而不是通过电子表格共享的,那么以下对网址的更改将会起作用

#Derive the id from the google drive shareable link.
#For the file at hand the link is as below
#<https://drive.google.com/open?id=1-tjNjMP6w0RUV4GhJWw08ql3wYwsNU69>
file_id='1-tjNjMP6w0RUV4GhJWw08ql3wYwsNU69'
link='https://drive.google.com/uc?export=download&id={FILE_ID}'
csv_url=link.format(FILE_ID=file_id)
#The final url would be as below:-
#csv_url='https://drive.google.com/uc?export=download&id=1-tjNjMP6w0RUV4GhJWw08ql3wYwsNU69'
df = pd.read_csv(csv_url)

数据框将是(如果你刚刚运行上面的代码)

    a   b   c   d
0   0   1   2   3
1   4   5   6   7
2   8   9   10  11
3   12  13  14  15

查看工作代码here

答案 6 :(得分:0)

这对我有用。

import pandas as pd

#Create a public URL
#https://docs.google.com/spreadsheets/d/0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc/edit?usp=sharing

#get spreadsheets key from url
gsheetkey = "0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc"

#sheet name
sheet_name = 'Sheet 1'

url=f'https://docs.google.com/spreadsheet/ccc?key={gsheetkey}&output=xlsx'
df = pd.read_excel(url,sheet_name=sheet_name)
print(df)
相关问题