How to Add List into a New Column in CSV - Python

adding list items into columns csv

Try this ( here I have used colum header as fields).There can be many other methods to achieve the same such as using NumPy or pandas library

import csv

#field names
fields = ['Name', 'Place', 'Number', 'Teplehone_Number'] # add more according to your data

# data rows of csv file
rows = [['Abendgymnasium Wiesbaden', 'Brunhildenstraße 140', '65189', 'Wiesbaden']] # add more according to your data

with open('output.csv', 'w') as f:

# using csv.writer method from CSV package
write = csv.writer(f)

write.writerow(fields)
write.writerows(rows)

How to append a list each time to a new column of a CSV file?

This might help you:

import pandas as pd
for a in range(1,10):
b = list(range(1,a+1))
if a==1:
df = pd.DataFrame({a:b})

else:
df = df.merge(pd.DataFrame({a:b}), how='outer', left_index=True, right_index=True)

When you print the df you'll get this:

    1   2   3   4   5   6   7   8   9
0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1
1 NaN 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2
2 NaN NaN 3.0 3.0 3.0 3.0 3.0 3.0 3
3 NaN NaN NaN 4.0 4.0 4.0 4.0 4.0 4
4 NaN NaN NaN NaN 5.0 5.0 5.0 5.0 5
5 NaN NaN NaN NaN NaN 6.0 6.0 6.0 6
6 NaN NaN NaN NaN NaN NaN 7.0 7.0 7
7 NaN NaN NaN NaN NaN NaN NaN 8.0 8
8 NaN NaN NaN NaN NaN NaN NaN NaN 9

Adding python lists as new columns to a csv file

The index of the source csv and the zipped lists should match so you can use enumerate to track it.

zipped = zip(list1, list2, list3, list4)

with open('in.csv', 'rb') as infile, open('out.csv' 'wb') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for i, row in enumerate(reader):
row.extend(zipped[i])
writer.writerow(row)

If you are doing a lot of data wrangling like this however check out the pandas library.
The pandas code is a bit simpler, although you have to get used to the pandas api, which is based on index labels and vectorised operations.

indata = pd.read_csv('in.csv')
zipped = pd.DataFrame(zip(List1, List2, List3, List4)
#axis=1 indicates to concat the frames column wise
outdata = pd.concat([indata, zipped], axis=1)
#we dont want headers and dont want the row labels
outdata.to_csv('out.csv', header=False, index=False)

Writing Python lists to columns in csv

Change them to rows:

rows = zip(list1, list2, list3, list4, list5)

Then just:

import csv

with open(newfilePath, "w") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)

Adding a Python list into the middle of an already populated CSV

Your code should almost work, you can use zip() to iterate over the input file and the list of phones at the same time, instead of using the i variable as a numerical index:

for row, phone in zip(csv.reader(csvinput), phone_list):
row[9] = phone
writer.writerow(row)

Now, if you're still getting that IndexError, that means your csv file has some line that doesn't contain 10 columns in first place (index 9 is the 10th column since indexes start at 0). Double-check your csv file. Try this testing code to check:

for row, phone in zip(csv.reader(csvinput), phone_list):
if len(row) < 10:
print('FOUND A ROW WITH {} COLUMNS: '.format(len(row)), row)
else:
row[9] = phone
writer.writerow(row)

Another solution is to add empty columns to complete the 10 columns to every row that has less than 10 columns:

for row, phone in zip(csv.reader(csvinput), phone_list):
row.extend(['']* (10 - len(row)))
row[9] = phone
writer.writerow(row)


Related Topics



Leave a reply



Submit