2016-09-26 114 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) 

希望這有助於一點點。