Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a single column Pandas DataFrame into Series

Tags:

python

pandas

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?

like image 603
neversaint Avatar asked Aug 22 '16 05:08

neversaint


3 Answers

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
like image 172
Alexander Avatar answered Nov 10 '22 01:11

Alexander


Try swapping the indices in the brackets:

df.iloc[:,0]

This should work.

like image 38
honza_p Avatar answered Nov 10 '22 00:11

honza_p


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
like image 1
Aman khan Roohaani Avatar answered Nov 10 '22 00:11

Aman khan Roohaani