我需要一些数据,我需要将它写入一列但不同的字符串
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
中的A1
,333
中的A5
等
我怎么能这样做?
答案 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)