Python中的数据与R相比(来自Excel工作表)

我在这里有一个假设的例子,附带的文件(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')] 

但我不知道如何将它粘贴到下一个循环中。

非常nb的问题反映了我对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) 

这只是一个build议:如果可以将excel工作表导出为csv,则可能需要查看numpy.genfromtxt : http : numpy.genfromtxt 。 io.genfromtxt.html

它似乎与pandas有类似的能力,但没有陡峭的学习曲线。 有delimiterautostripmissing_valuesfilling_values ,列names和列是以numpy.arrayforms。