Output a DataFrame to CSV

o write a DataFrame as a CSV file, you can use to_csv():

import pandas as pd
df.to_csv('myDataFrame.csv')

That piece of code seems quite simple, but this is just where the difficulties begin for most people because you will have specific requirements for the output of your data. Maybe you don’t want a comma as a delimiter, or you want to specify a specific encoding, …

Don’t worry! You can pass some additional arguments to to_csv() to make sure that your data is outputted the way you want it to be!

  • To delimit by a tab, use the sep argument:

    import pandas as pd
    df.to_csv('myDataFrame.csv', sep='\t')
  • To use a specific character encoding, you can use the encoding argument:

    import pandas as pd
    df.to_csv('myDataFrame.csv', sep='\t', encoding='utf-8')
  • Furthermore, you can specify how you want your NaN or missing values to be represented, whether or not you want to output the header, whether or not you want to write out the row names, whether you want compression, … Read up on the options here.

https://www.datacamp.com/community/tutorials/pandas-tutorial-dataframe-python

Last updated

Was this helpful?