Salvataggio di un Dataframe Pandas come CSV

Salvataggio di un Dataframe Pandas come CSV

In questo articolo impareremo come esportare un Pandas DataFrame in un file CSV utilizzando il metodo Pandas to_csv(). Per impostazione predefinita, il metodo to csv() esporta DataFrame in un file CSV con indice di riga come prima colonna e virgola come delimitatore.

Creazione di DataFrame per esportare Pandas DataFrame in CSV

Python3




# importing pandas as pd> import> pandas as pd> # list of name, degree, score> nme> => [> 'aparna'> ,> 'pankaj'> ,> 'sudhir'> ,> 'Geeku'> ]> deg> => [> 'MBA'> ,> 'BCA'> ,> 'M.Tech'> ,> 'MBA'> ]> scr> => [> 90> ,> 40> ,> 80> ,> 98> ]> # dictionary of lists> dict> => {> 'name'> : nme,> 'degree'> : deg,> 'score'> : scr}> > df> => pd.DataFrame(> dict> )> print> (df)>

Produzione:

 name degree score 0 aparna MBA 90 1 pankaj BCA 40 2 sudhir M.Tech 80 3 Geeku MBA 98 

Esporta CSV in una directory di lavoro

Qui, esportiamo semplicemente un Dataframe in un file CSV utilizzando df.to_csv().

Python3




# saving the dataframe> df.to_csv(> 'file1.csv'> )>

Produzione:

Salvataggio di un Dataframe Pandas come CSV

Salvataggio CSV senza intestazioni E indice .

Qui stiamo salvando il file senza intestazione e senza numero di indice.

Python3




# saving the dataframe> df.to_csv(> 'file2.csv'> , header> => False> , index> => False> )>

Produzione:

Salvataggio di un Dataframe Pandas come CSV

Salva il file CSV in una posizione specificata

Possiamo anche salvare il nostro file in una posizione specifica.

Python3




# saving the dataframe> df.to_csv(r> 'C:UsersAdminDesktopfile3.csv'> )>

Produzione:

Scrivi un DataFrame in un file CSV utilizzando il separatore di tabulazioni

Possiamo anche salvare il nostro file con alcune specifiche separate come vogliamo. cioè .

Python3




import> pandas as pd> import> numpy as np> users> => {> 'Name'> : [> 'Amit'> ,> 'Cody'> ,> 'Drew'> ],> > 'Age'> : [> 20> ,> 21> ,> 25> ]}> #create DataFrame> df> => pd.DataFrame(users, columns> => [> 'Name'> ,> 'Age'> ])> print> (> 'Original DataFrame:'> )> print> (df)> print> (> 'Data from Users.csv:'> )> df.to_csv(> 'Users.csv'> , sep> => ' '> , index> => False> ,header> => True> )> new_df> => pd.read_csv(> 'Users.csv'> )> print> (new_df)>

Produzione:

Original DataFrame: Name Age 0 Amit 20 1 Cody 21 2 Drew 25 Data from Users.csv: Name	Age 0 Amit	20 1 Cody	21 2 Drew	25