1

我在这里有一个带有附加文件(Excel 文件链接)的假设示例,我在其中从 excel 加载文件并将其格式化为我可以使用的东西来分析或更永久地存储。

在 RI 中将使用以下几行使其可用:

library(gdata)
tmp = read.xls('~/Desktop/sample.xlsx',1,stringsAsFactors=F)
tmp = tmp[,!sapply(tmp,function(x)all(is.na(x)))]
tmp$date = tmp[1,2]
for(i in 2:ncol(tmp)){ifelse(tmp[2,i]=='',tmp[2,i]<-tmp[2,i-1],tmp[2,i]<-tmp[2,i])}
tmp[2,1]=tmp[1,1]
names(tmp)=paste(tmp[2,],tmp[3,],sep='.')
tmp=tmp[-c(1:3),]
names(tmp)[10]='date'

在python中 - 我已经做到了

import xlrd

myf='/home/me/Desktop/sample.xlsx'

sheet = xlrd.open_workbook(myf).sheet_by_index(0)

s1=[]
r = sheet.nrows
c = sheet.ncols
for row in range(0,r):
    t1=[]
    for col in range(0,c):
        t1.append(sheet.cell_value(row,col))
    s1.append(t1)

但后来我在摆脱空行和空列方面收效甚微。以下所有失败。

>>> s1[0]
['', '', '', '', '', '', '', '', '', '', '', '']
>>> s1[0] == []
False
>>> s1[0] == ''
False
>>> s1[0] == all('')
False

所以我什至不太清楚如何检查整个列表是否为空。

我可以压缩第 2 行和第 3 行(python 中的第 5 行和第 6 行)

>>> zip(s1[5],s1[6])
[('', ''), (u'cat1', u'a'), ('', u'b'), ('', ''), (u'cat2', u'c'), ('', u'd'), ('', ''), (u'cat3', u'e'), ('', u'f'), ('', ''), (u'cat4', u'g'), ('', u'h')]

但我不知道如何将其粘贴到 for-next 循环中。

非常n00b的问题反映了我对python的理解。任何想法都会受到欢迎。提交时有些不安,因为我认识到这个问题有一种“家庭作业”的感觉,尽管它实际上是一个个人学习练习。谢谢

经过一番混乱后,我在下面设计了一个粗略且现成的工作示例:将不胜感激有关如何更有效地执行此操作的指示。

我尝试过 pandas,但发现学习曲线非常陡峭。如果有人可以发布有效的 MWE,我很乐意将其标记为已回答。

import os
import xlrd
import pandas as pd
import pprint
import re
import csv

''' 
Create a few helper functions to save time 
finding things, picking empties and selecting items
'''

def nulls(x):
    g = lambda r: all(i == '' for i in r)
    out = [i for i,j in enumerate(x) if g(j)]
    return(out)

def fill(x):
    for i in range(1,len(x)):
        if x[i] == '':
            x[i] = x[i-1]
    return(x)

def which(x,y):
    out = [i for i,j in enumerate(x) if y(j) ]
    return(out)

def T(x):
    out = map(list,zip(*x))
    return(out)

def rbind(x,y,sep=None):
    if sep is None:
        sep='.'
    out = [str(i[0]) + sep + str(i[1]) for i in zip(x,y)]
    return(out)

# def csvit(x):
#   tmp = next(key for key,val in globals().items() if val == x and not key.startswith('_'))
#   f=open('/home/me/Desktop/csvs/'+tmp+'.csv','wb')
#   writer = csv.writer(f,quotechar='"', quoting=csv.QUOTE_ALL,dialect=csv.excel)
#   [writer.writerow(i) for i in x]
#   f.close()


#
# Load spreadsheet from file and convert to python list
#

sheet = xlrd.open_workbook('/home/me/Downloads/sample.xlsx').sheet_by_index(0)
s = [sheet.row_values(i) for i in range(sheet.nrows)]

#
# Get rid of unnecessary excel formatting and spacing
#

# rows first
s = [j for i,j in enumerate(s) if i not in nulls(s)]

# transpose & then columns (surely there is a more elegant way?)
s = T(s)
s = [j for i,j in enumerate(s) if i not in nulls(s)]

# get title for primary category column
title = s[0][0]

# get date for secondary category column
date = [j[1] for j in s if str(j[0]) == 'date']

#
# combine columns into a single category variable (could also have left them separate)
#

cols=['Category']
s = T(s)
cols.extend(rbind(fill(s[2]),s[3])[1:])
s = s[4:len(s)] 

s=T(s)
category = [str(i) for i in s[0]]
s=s[1:len(s)]

c1=[date for i in range(len(s[0]))] #create date column
c2=[title for i in range(len(s[0]))] #create title column
cols.insert(0,'title')
cols.insert(1,'date')
s.insert(0,c2)
s.insert(1,c1)

s = T(s)
4

1 回答 1

1

这只是一个建议:如果您可以将 excel 工作表导出为 csv,您可能想看看numpy.genfromtxthttp ://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt .html

它似乎具有与 pandas 相似的功能,但没有陡峭的学习曲线。有delimiter, autostrip, missing_values, filling_values, 列names, 列在numpy.array形式中。

于 2013-07-02T14:14:12.020 回答