如何将单列Pandas DataFrame转换为Series

时间:2016-08-22 05:37:39

标签: python pandas

我有以下数据框:

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

哪个使:

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

我想要做的是把它变成一个系列。 我希望它能够回归:

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

我试过了,但它没有用:

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

做正确的方法是什么?

3 个答案:

答案 0 :(得分:11)

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

要将其恢复到数据框:

>>> s.to_frame()
      score
gene       
foo       4
bar       3

答案 1 :(得分:4)

尝试交换括号中的索引:

df.iloc[:,0]

这应该有用。

答案 2 :(得分:1)

交换索引可以轻松解决问题:

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
相关问题