Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas dataframe transpose, to_csv

In the code below, in line 4 I can transpose the dataframe, but in line 5, when I use to_csv, the new CSV file is created, it remains the original version and not the transposed one. What might have gone wrong?

import numpy as np
import pandas as pd

df = pd.read_csv('~/N.csv')

df2 = df.T

df2 = df.to_csv('~/N_transposed.csv')

Thank you!

like image 354
Coloane Avatar asked Apr 07 '14 22:04

Coloane


2 Answers

No need to use df2 =

This is enough..

df2.to_csv('~/N_transposed.csv')
like image 67
chucklukowski Avatar answered Nov 02 '22 23:11

chucklukowski


In line 5, use

df3 = df2.to_csv('~/N_transposed.csv') 

or

 df2.to_csv('~/N_transposed.csv') 

The df variable has not been altered, the result is stored in df2 and that's what you need to output to csv, not df.to_csv.

like image 31
Anshul Goyal Avatar answered Nov 03 '22 01:11

Anshul Goyal