2016-09-26 111 views
0

的代码的部分的Excel元值示于下用0填充

import collections 
import csv 
import sys 


with open("321.csv","r") as f: 
    cr = csv.reader(f,delimiter=",") 
    d=collections.defaultdict(lambda : list()) 
    header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method. 
    for r in cr: 
     d[r[0]].append(r[1]) # fill dict 


with open("sorted output.csv","w") as f: 

    cr = csv.writer(f,sys.stdout, lineterminator='\n') 

    od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value 
    for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs 
     v = [ord(i) for i in v] # convert letters into numbers 

     cr.writerow(v) 

使我这个输出:

enter image description here

欲填在该区域的所有空单元:(A1: :X30)用0s(每次应该用0填充的单元格由最大行的长度定义,例如,如果最大的行具有直到Y列的元素,那么应当填充0的空单元将处于该地区(A1 :: Y30))

你能帮忙吗?

回答

2

我还没有测试,但也许这?

import collections 
import csv 
import sys 

max_len = 0 
with open("321.csv","r") as f: 
    cr = csv.reader(f,delimiter=",") 
    d=collections.defaultdict(lambda : list()) 
    header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method. 
    for r in cr: 
     d[r[0]].append(r[1]) # fill dict 
     max_len = max(len(d[r[0]]), max_len) 

with open("sorted output.csv","w") as f: 

    cr = csv.writer(f,sys.stdout, lineterminator='\n') 

    od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value 
    for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs 
     v = [ord(i) for i in v] + [0]*(max_len - len(v)) # convert letters into numbers 

     cr.writerow(v) 
1

我不太清楚,如果我正确理解你的问题。下面是一个尝试:

创建具有只是0的另一种可能是如下使用熊猫和numpy的一个XLS文件:

import pandas as pd 
import numpy as np 
import io 

number_of_rows = 30 
number_of_columns = 24 

# Create a dataframe of 0's in the dimension you define above 
df = pd.DataFrame(np.array([np.zeros(number_of_columns) for i in range(number_of_rows)])) 

# Give out as xls file 
df.to_excel('output.xls', index=False) 

如果你希望有一定的细胞与非零和休息用零,你可以很容易地(前df.to_excle)通过改写的东西像您所选择的功能如下:

df.set_values(row,column,value) 

希望这有助于一点点。