> ## Content Index
> Fetch the complete content index at: https://datascientyst.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Dump (unique) values to CSV / to_csv in Pandas
- URL: https://datascientyst.com/dump-unique-values-to-csv-to_csv-pandas/
- Published: 2021-11-03T07:10:45.000Z
- Updated: 2021-11-03T07:10:45.000Z
- Author: John D K
- Tags: to_csv()

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:

```python
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`:

```python
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`:

```python
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`

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

```

## Resources

- [Notebook](https://github.com/softhints/Pandas-Tutorials/blob/master/to%5Fcsv/dump-unique-values-to-csv-to%5Fcsv-pandas.ipynb?ref=datascientyst.com)
- [pandas.DataFrame.to\_csv](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to%5Fcsv.html?highlight=to%5Fcsv&ref=datascientyst.com#pandas.DataFrame.to%5Fcsv)
- [pandas.Series.to\_csv](https://pandas.pydata.org/docs/reference/api/pandas.Series.to%5Fcsv.html?highlight=to%5Fcsv&ref=datascientyst.com#pandas.Series.to%5Fcsv)