2016-09-26 4 views
0

The части кода показано нижезначения 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) с 0. (Каждый раз, когда ячейки, которые должны быть заполнены 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

Я не совсем уверен, правильно ли понял ваш вопрос. Вот попытка:

Чтобы создать файл XLS, который имеет только 0 альтернативы могла бы использовать панда и NumPy следующим образом:

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) 

Надеется, что помогло немного.

Смежные вопросы