如何将单列Pandas DataFrame转换为Series

8
我可以帮助您进行翻译。以下是数据框的内容:

我有以下数据框:

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

我可以帮您进行翻译。需要将其转换为一个Series。我期望它返回:
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个回答

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

将其转换回数据框架:

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

1
参见https://dev59.com/KFwX5IYBdhLWcg3w6S8h#40208359 - Alexander
请注意,如果您的DataFrame只有一个元素,则squeeze()将返回一个标量。这样,iloc[:,0]将返回更一致的结果。 - Jonathan Biemond

11

尝试交换方括号中的索引:

df.iloc[:,0]

这应该可以运行。


请注意下面 @Alexander 给出的答案。如果有多列,则这个答案会导致歧义。Squeeze 简单地失败了,这正是你经常想要的结果。 - Eli S

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接