How to get the first column of a pandas DataFrame as a Series? How to get the first column of a pandas DataFrame as a Series? python python

How to get the first column of a pandas DataFrame as a Series?


>>> import pandas as pd>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})>>> df   x  y0  1  41  2  52  3  63  4  7>>> s = df.ix[:,0]>>> type(s)<class 'pandas.core.series.Series'>>>>

===========================================================================

UPDATE

If you're reading this after June 2017, ix has been deprecated in pandas 0.20.2, so don't use it. Use loc or iloc instead. See comments and other answers to this question.


From v0.11+, ... use df.iloc.

In [7]: df.iloc[:,0]Out[7]: 0    11    22    33    4Name: x, dtype: int64


You can get the first column as a Series by following code:

x[x.columns[0]]