如何将单列 Pandas DataFrame 转换为 Series

问题描述 投票:0回答:4

我有以下数据框:

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

正确的做法是什么?

python pandas
4个回答
28
投票
s = df.squeeze()
>>> s
gene
foo    4
bar    3
Name: score, dtype: float64

将其恢复为数据框:

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

11
投票

尝试交换括号中的索引:

df.iloc[:,0]

这应该有效。


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

0
投票

在 2.2.1 中,这些访问将列

score
作为系列返回

  • df.score
    --> 将单个列作为属性访问
  • df['score']
    --> 通过标签访问列
  • df.get('score')
    --> 获取列项

加上列的常规索引:

  • df.iloc[:, 0]
    --> 按位置访问项目
  • df.loc[:, 'score']
    --> 通过标签访问项目

df['score']
是最合乎逻辑的方式,如果你的列名是有效的标识符,它可以缩写为
df.score
(尽管这个快捷方式很脆弱)。


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

print(df.score)
print(df['score'])
print(df.iloc[:,0])
print(df.loc[:,'score'])
print(df.get('score'))

所有结果:

gene
foo    4.0
bar    3.0
Name: score, dtype: float64
© www.soinside.com 2019 - 2024. All rights reserved.