Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To_CSV unique values of a pandas column [duplicate]

When I use the following:

import pandas as pd
data = pd.read_csv('C:/Users/Z/OneDrive/Python/Exploratory Data/Aramark/ARMK.csv')
x = data.iloc[:,2]
y = pd.unique(x)
y.to_csv('yah.csv')

I get the following error:

AttributeError: 'numpy.ndarray' object has no attribute 'to_csv'
like image 631
ZJAY Avatar asked Mar 19 '16 21:03

ZJAY


2 Answers

IIUC, starting from a dataframe:

df = pd.DataFrame({'a':[1,2,3,4,5,6],'b':['a','a','b','c','c','b']})

you can get the unique values of a column with:

g = df['b'].unique()

that returns an array:

array(['a', 'b', 'c'], dtype=object)

to save it into a .csv file I would transform it into a Series s:

In [22]: s = pd.Series(g)

In [23]: s
Out[23]: 
0    a
1    b
2    c
dtype: object

So you can easily save it:

In [24]: s.to_csv('file.csv')

Hope that helps.

like image 52
Fabio Lamanna Avatar answered Nov 03 '22 16:11

Fabio Lamanna


The pandas equivalent of np.unique is the drop_duplicates method.

In [42]: x = pd.Series([1,2,1,3,2])

In [43]: y = x.drop_duplicates()

In [46]: y
Out[46]: 
0    1
1    2
3    3
dtype: int64

Notice that drop_duplicates returns a Series, so you can call its to_csv method:

import pandas as pd
data = pd.read_csv('C:/Users/Z/OneDrive/Python/Exploratory Data/Aramark/ARMK.csv')
x = data.iloc[:,2]
y = x.drop_duplicates()
y.to_csv('yah.csv')
like image 44
unutbu Avatar answered Nov 03 '22 15:11

unutbu