Dump (unique) values to CSV / to_csv in Pandas

This post will show you how to use to_csv in Pandas and avoid errors like:

AttributeError: 'numpy.ndarray' object has no attribute 'to_csv'

For example if you like to write unique values from Pandas to a CSV file by method to_csv from this data:

Date Time Latitude Longitude Depth Magnitude Type
01/02/1965 13:44:18 19.246 145.616 131.6 MW
01/04/1965 11:29:49 1.863 127.352 80.0 MW
01/05/1965 18:05:58 -20.579 -173.972 20.0 MW
01/08/1965 18:49:43 -59.076 -23.557 15.0 MW
01/09/1965 13:32:50 11.938 126.427 15.0 MW

by:

df['Magnitude Type'].unique().to_csv()

This will result into:

AttributeError: 'numpy.ndarray' object has no attribute 'to_csv'

The reason for the error is that method unique returns an array and not pd.Series or pd.DataFrame object:

array(['MW', 'ML', 'MH', 'MS', 'MB', 'MWC', 'MD', nan, 'MWB', 'MWW',
   'MWR'], dtype=object)

For Pandas you have two different option depending on your context.

Series

Convert the result of method unique to a Pandas Series by pd.Series:

pd.Series(df['Magnitude Type'].unique()).to_csv('data.csv')

DataFrame

If the pd.Series it's not suitable or doesn't work for your case then you can use pd.DataFrame:

pd.DataFrame(df['Magnitude Type'].unique()).to_csv('data.csv')

Skip headers and index

Finally if you like to exclude the headers and the index from the output CSV file you can use arguments: header=None, index=None

pd.DataFrame(df['Magnitude Type'].unique()).to_csv('data.csv', header=None, index=None)

Resources