簡體   English   中英

python中的數據處理與R(來自excel工作表)相比

[英]data munging in python compared with R (from an excel sheet)

我在這里有一個假設的示例,帶有附加文件(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的理解。 任何想法都將受到歡迎。 提交時有些不安,因為我知道這個問題雖然實際上是個人學習,但卻具有“作業”的感覺。 謝謝

經過一番混亂之后,我整理了下面的一個大致而可行的示例:感謝您提供有關如何更有效地執行操作的指示。

我嘗試過熊貓,但發現學習曲線相當陡峭。 如果有人可以發布正在運行的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.genfromtxthttp : numpy.genfromtxt 。 io.genfromtxt.html

它似乎具有與熊貓相似的功能,但沒有陡峭的學習曲線。 具有delimiterautostripmissing_valuesfilling_values ,列names ,並且numpy.array形式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM