python - python 与 R 中的数据整理比较(来自 Excel 工作表)

标签 python r excel data-munging

我这里有一个假设的例子,附加了文件 (Excel File Link)我从 Excel 加载一个文件,并将其格式化为我可以使用的内容,以进行分析或更永久地存储。

在 R 中,我将使用以下几行来使其可用:

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的问题反射(reflect)了我对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)

最佳答案

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

它似乎具有与 pandas 类似的功能,但没有陡峭的学习曲线。具有 delimiterautostripmissing_valuesfilling_values、列 names 和列采用 numpy.array 形式。

关于python - python 与 R 中的数据整理比较(来自 Excel 工作表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16672547/

相关文章:

excel - 如何根据Excel中的IF条件将公式应用于单元格

c++ - 从 Excel 文件读取特定列到 C++

python - "force"用户使用带有 argparse 的特定文件扩展名的最佳方法是什么?

python - 使用 django 将 CSV 文件导入 postgres

python - 根据条件连接列表中的元素

python - 为什么以下代码给出不同的输出? (大数的平方根)

r - 从R?中的zeroinfl对象没有预测到零。

r - 如何与 Quanteda 建立互动?

mysql - Excel VBA MySql 参数化更新 'invalid parameter type'

python - R 或 Python 中的频繁模式增长