gpt4 book ai didi

python - 将电子表格的列存储在 Python 字典中

转载 作者:太空狗 更新时间:2023-10-29 22:22:19 24 4
gpt4 key购买 nike

我有一个表格存储在 Excel 文件中,如下所示:

Species     Garden Hedgerow Parkland Pasture WoodlandBlackbird       47       10      40        2        2Chaffinch       19        3       5        0        2Great Tit       50        0      10        7        0House Sparrow   46       16       8        4        0Robin            9        3       0        0        2Song Thrush      4        0       6        0        0

I am using the xlrd Python library for reading these data. I have no problem reading it into a list of lists (with each line of the table stored as a list), using the code below:

from xlrd import open_workbook
wb = open_workbook("Sample.xls")
headers = []
sdata = []
for s in wb.sheets():
print "Sheet:",s.name
if s.name.capitalize() == "Data":
for row in range(s.nrows):
values = []
for col in range(s.ncols):
data = s.cell(row,col).value
if row == 0:
headers.append(data)
else:
values.append(data)
sdata.append(values)

很明显,headers 是一个存储列标题的简单列表,sdata 包含表数据,存储为列表列表。这是他们的样子:

标题:

[u'Species', u'Garden', u'Hedgerow', u'Parkland', u'Pasture', u'Woodland']

数据:

[[u'Blackbird', 47.0, 10.0, 40.0, 2.0, 2.0], [u'Chaffinch', 19.0, 3.0, 5.0, 0.0, 2.0], [u'Great Tit', 50.0, 0.0, 10.0, 7.0, 0.0], [u'House Sparrow', 46.0, 16.0, 8.0, 4.0, 0.0], [u'Robin', 9.0, 3.0, 0.0, 0.0, 2.0], [u'Song Thrush', 4.0, 0.0, 6.0, 0.0, 0.0]]

但我想将这些数据存储到 Python 字典中,每一列作为包含每一列所有值的列表的键。例如(为了节省篇幅只展示了部分数据):

dict = {
'Species': ['Blackbird','Chaffinch','Great Tit'],
'Garden': [47,19,50],
'Hedgerow': [10,3,0],
'Parkland': [40,5,10],
'Pasture': [2,0,7],
'Woodland': [2,2,0]
}

所以,我的问题是:我怎样才能做到这一点?我知道我可以按列而不是按行读取数据,就像上面的代码片段一样,但我不知道如何将列存储在字典中。

在此先感谢您提供的任何帮助。

最佳答案

1 。 XLRD

我强烈建议使用 collections 中的 defaultdict图书馆。每个键的值将使用默认值启动,在本例中为空列表。我没有在那里放那么多异常捕获,您可能想根据您的用例添加异常检测。

import xlrd
import sys
from collections import defaultdict
result = defaultdict(list)
workbook = xlrd.open_workbook("/Users/datafireball/Desktop/stackoverflow.xlsx")
worksheet = workbook.sheet_by_name(workbook.sheet_names()[0])

headers = worksheet.row(0)
for index in range(worksheet.nrows)[1:]:
try:
for header, col in zip(headers, worksheet.row(index)):
result[header.value].append(col.value)
except:
print sys.exc_info()

print result

输出:

defaultdict(<type 'list'>, 
{u'Garden': [47.0, 19.0, 50.0, 46.0, 9.0, 4.0],
u'Parkland': [40.0, 5.0, 10.0, 8.0, 0.0, 6.0],
u'Woodland': [2.0, 2.0, 0.0, 0.0, 2.0, 0.0],
u'Hedgerow': [10.0, 3.0, 0.0, 16.0, 3.0, 0.0],
u'Pasture': [2.0, 0.0, 7.0, 4.0, 0.0, 0.0],
u'Species': [u'Blackbird', u'Chaffinch', u'Great Tit', u'House Sparrow', u'Robin', u'Song Thrush']})

2。 Pandas

import pandas as pd
xl = pd.ExcelFile("/Users/datafireball/Desktop/stackoverflow.xlsx")
df = xl.parse(xl.sheet_names[0])
print df

输出,您无法想象使用 DataFrame 可以获得多大的灵 active 。

             Species  Garden  Hedgerow  Parkland  Pasture  Woodland
0 Blackbird 47 10 40 2 2
1 Chaffinch 19 3 5 0 2
2 Great Tit 50 0 10 7 0
3 House Sparrow 46 16 8 4 0
4 Robin 9 3 0 0 2
5 Song Thrush 4 0 6 0 0

关于python - 将电子表格的列存储在 Python 字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26289346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com