Henrique Vital
Henrique Vital

Reputation: 103

How to insert a text in the last row and in a specific column of an csv file using pandas?

I am trying to insert a text in the last row and in a specific column of a csv file, I already search on the internet but I don´t find any solution.

In the example below I just want to add an email.

Example:

Name, Age, email
Jake, 23, [email protected]
Camila, , Camila,outlook.com
, , [email protected]   <- The line that I want to add

my code:

df = pd.DataFrame(columns=header)
df.to_csv(str(day) + '_' + str(month) + '_' + str(year) + '.csv', 
          sep=',',
          header=True,
          index=False)
df.loc[df.shape[0], 'Campaign'] = 'hi'

Upvotes: 0

Views: 752

Answers (1)

Chris
Chris

Reputation: 29742

You must use to_csv as a last line:

header = ["Name", "Age", "email"]

df = pd.DataFrame(columns=header)

df.loc[df.shape[0], 'email'] = '[email protected]'
df.to_csv("stackoverflow.csv", 
          index=False)

Output:

Name,Age,email
,,[email protected]

Upvotes: 1

Related Questions