8

I have the following data frame:

import pandas as pd
d = {'gene' : ['foo','bar'],'score' : [4., 3.,]}
df = pd.DataFrame(d)
df.set_index('gene',inplace=True)

Which make:

In [56]: df
Out[56]:
      score
gene
foo       4
bar       3
In [58]: type(df)
Out[58]: pandas.core.frame.DataFrame

What I want to do is to turn it into a Series. I expect it to to return:

gene
foo       4
bar       3
#pandas.core.series.Series

I tried this but it doesn't work:

In [64]: type(df.iloc[0:,])
Out[64]: pandas.core.frame.DataFrame

In [65]: df.iloc[0:,]
Out[65]:
      score
gene
foo       4
bar       3

What's the right way to do it?

neversaint
  • 60,904
  • 137
  • 310
  • 477

3 Answers3

28
s = df.squeeze()
>>> s
gene
foo    4
bar    3
Name: score, dtype: float64

To get it back to a dataframe:

>>> s.to_frame()
      score
gene       
foo       4
bar       3
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • 1
    See also https://stackoverflow.com/questions/33246771/convert-pandas-data-frame-to-series/40208359#40208359 – Alexander Oct 02 '18 at 19:39
  • Note that if your DataFrame is of a single element, `squeeze()` will return a scalar. In this way `iloc[:,0]` will return a more consistent result. – Jonathan Biemond May 11 '23 at 16:01
11

Try swapping the indices in the brackets:

df.iloc[:,0]

This should work.

honza_p
  • 2,073
  • 1
  • 23
  • 37
  • Note also @Alexander's answer below. This answer will lead to ambiguity if there is more than one column. Squeeze simply fails and that is what you often want. – Eli S Feb 25 '21 at 17:15
1

Swapping the indices would solve the problem easily:

In [64]: type(df.iloc[0:,])
Out[64]: pandas.core.frame.DataFrame

In [65]: df.iloc[[:,0] // Swaped the indices
Out[65]:
        score
gene
foo       4
bar       3