'How to save a list as a .csv file with python and pandas?
I have three lists:
title = ['title1', 'title2', 'title3']
emails = ['1@1', '1@2', '1@3']
links = ['http1', 'http2', 'http3']
I need to insert each of these lists to a column in the CSV file. In the next iteration, I erase the data from the lists and they are filled with new data which also needs to go into these columns without overwriting the previous data.
Example of table:
| Titles | Emails | Links |
|---|---|---|
| title1 | 1@1 | http1 |
| title2 | 1@2 | http2 |
| title3 | 1@3 | http3 |
| title4 | 1@4 | http4 |
| title5 | 1@5 | http5 |
| title6 | 1@6 | http6 |
I tried the following:
df.to_csv('content.csv', index=False, columns=list['Titles', 'Emails', 'Links'])
df['Titles'] = titles
df['Emails'] = emails
df['Links'] = links
But it returns the error: pandas.errors.EmptyDataError: No columns to parse from file
Solution 1:[1]
You need to create a DataFrame object first, then assign the data and finally save it as a csv file:
import pandas as pd
titles = ["Mr", "Ms", "Mrs"]
emails = ["[email protected]", "[email protected]", "[email protected]"]
links = ["https://www.cbc.ca", "https://www.srf.ch", "https://www.ard.de"]
df = pd.DataFrame(columns=["Titles", "Emails", "Links"])
df["Titles"] = titles
df["Emails"] = emails
df["Links"] = links
df.to_csv("content.csv", index=False)
You can also assign the data to the DataFrame object right away when creating it:
import pandas as pd
titles = ["Mr", "Ms", "Mrs"]
emails = ["[email protected]", "[email protected]", "[email protected]"]
links = ["https://www.cbc.ca", "https://www.srf.ch", "https://www.ard.de"]
df = pd.DataFrame({
"Titles": titles,
"Emails": emails,
"Links": links
})
df.to_csv("content.csv", index=False)
And if you need to append to the csv file use mode="a":
df = pd.DataFrame({
"Titles": ["Ms"],
"Emails": ["[email protected]"],
"Links": ["https://www.orf.at"]
})
# appends the new data to the csv file
df.to_csv("content.csv", mode="a", index=False, header=False)
Solution 2:[2]
You first need to create a dataframe and then assign to each column and then export to csv:
titles = ['title1', 'title2', 'title3']
emails = ['1@1','1@2','1@3']
links = ['http1', 'http2', 'http3']
#Create Dataframe
df = pd.DataFrame()
#assign columns
df['Titles'] = titles
df['Emails'] = emails
df['Links'] = links
# export to csv
df.to_csv('content.csv', index=False, columns=['Titles', 'Emails', 'Links'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Hamza |
