Excel单元格值填充为0

时间:2016-09-26 10:06:12

标签: python excel

下面显示的部分代码

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

我想用0填充区域中的所有空单元格:(A1 :: X30)。(每次应该用0填充的单元格由最大行的长度定义。例如,如果最大的行有直到列Y的元素应该用0填充的空单元格将在区域中(A1 :: Y30))

你能帮忙吗?

2 个答案:

答案 0 :(得分: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 :(得分:1)

我不太确定我是否理解你的问题。这是一次尝试:

要创建一个只有0的xls文件,可以选择使用pandas和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)

希望有所帮助。