Home > Software engineering >  How to save a list as a .csv file with python and pandas?
How to save a list as a .csv file with python and pandas?

Time:04-20

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

CodePudding user response:

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

CodePudding user response:

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)
  • Related