1

I need some data and I need write it to one column but to different string

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])

I want to write elem1 to cell with number elem2, i mean 111 in A1, 333 in A5 etc. How can I do that?

2
  • what do you want to write in the in-between rows? Commented Feb 4, 2017 at 13:24
  • @Jean-FrançoisFabre it will be empty, but I need to write it in loop and numbers may be not in order Commented Feb 4, 2017 at 13:27

1 Answer 1

1

So initialize your list with empty values according to list2 max index. Then, fill it according to list1,list2 indexes/values tuples using zip as you did in your attempt.

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

At this point rows_to_write is worth:

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

then write the rows in 1 instruction (don't append)

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

This creates a single-row "sparse" csv file. (open('hh1.csv', 'wb') as f for python 2)

Sign up to request clarification or add additional context in comments.

6 Comments

It write 111 to cell 1, 113, 225
it's not even possible. Those values are not in list2 range... oh, you have to use w mode not a !! rewrite the file from zero.
Can you say, but if I don't have a list with numbers, but get it in loop, can i write like this in loop?
I try to do that, but it don't write that
probably a newline issue. Check my edit on open of the .csv file
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.