Python:将数据写入特定单元格

时间:2017-02-04 13:21:50

标签: python csv

我需要一些数据,我需要将它写入一列但不同的字符串

df = pd.DataFrame()
list1 = ['111', '333', '555', '777', '8888']
list2 = [1, 5, 56, 44, 2]
with open('hh1.csv', 'a') as f:
    writer = csv.writer(f)
    for (elem1, elem2) in zip(list1, list2):
        writer.writerow([elem1])

我想将elem1写入编号为elem2的单元格,我的意思是 111中的A1333中的A5等 我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

因此,根据list2 max index,使用空值初始化列表。然后,使用list1,list2根据zip索引/值元组填充它,就像在尝试时一样。

list1 = ['111', '333', '555', '777', '8888']
list2 = [1, 5, 56, 44, 2]
rows_to_write = [[""] for _ in range(max(list2))]
for i,v in zip(list2,list1):
    rows_to_write[i-1][0] = v

此时rows_to_write值得:

[['111'], ['8888'], [''], [''], ['333'], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], ['777'], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], [''], ['555']]

然后在1条指令中写入行(不要追加)

with open('hh1.csv', 'w',newline='') as f: # python 3
    csv.writer(f).writerows(rows_to_write)

这会创建一个单行"稀疏" csv文件。 (open('hh1.csv', 'wb') as f for python 2)