theo1010
theo1010

Reputation: 137

Write to_csv with Python Pandas: Choose which column index to insert new data

I have a set of data output in my program that I want to write to a .csv file. I am able to make a new file with the old input data, followed by the new data in the last column to the right. How can I manipulate which column my output data goes to? Also, how can I choose to not include the old input data in my new file? I'm new to pandas.

Thanks!

Upvotes: 3

Views: 1747

Answers (1)

Maksim Khaitovich
Maksim Khaitovich

Reputation: 4792

Loading from file:

import pandas as pd
df = pd.read_csv('D:\\Apps\\Coursera\\Kaggle-Titanic\\Data\\train.csv', header = 0)

Some manipulation:

df['Gender'] = df.Sex.map(lambda x: 0 if x=='female' else 1)
df['FamilySize'] = df.SibSp + df.Parch

Copy some fields to new:

result = df[['Sex', 'Survived', 'Age']]

Delete not needed fields:

del result['Sex']

Save to the file:

result.to_csv('D:\\Apps\\Coursera\\Kaggle-Titanic\\Swm\\result.csv', index=False)

Or if you want to save only some fields or in some specific order:

df[['Sex', 'Survived', 'Age']].to_csv('D:\\Apps\\Coursera\\Kaggle-Titanic\\Swm\\result.csv', index=False)

Upvotes: 2

Related Questions