I have a list of tuples ordered by value. They are in the form (name,count)
where count is number of occurrences for each unique name.
I would like to take this list and transform it into CSV where each name is column header and each value is column value of a single row.
Any suggestions how to do it? Thanks.
You can convert a list of tuples to a CSV file by using NumPy's savetext() function and passing the NumPy array as an argument that arises from the conversion of the list of tuples.
Using Pandas to_csv() function To convert the list to csv, we need to convert from list to dataframe and then use the to_csv() function to convert dataframe to a csv file. In this example, we have first imported pandas library and then define the four lists and map it with its column using a dictionary.
Tuple order is as you insert values into the tuple. They're not going to be sorted as I think you're asking. zip will again, retain the order you inserted the values in.
You can do this:
import csv # note: If you use 'b' for the mode, you will get a TypeError # under Python3. You can just use 'w' for Python 3 data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)] with open('ur file.csv','wb') as out: csv_out=csv.writer(out) csv_out.writerow(['name','num']) for row in data: csv_out.writerow(row) # You can also do csv_out.writerows(data) instead of the for loop
the output file will have:
name,num "smith, bob",2 carol,3 ted,4 alice,5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With