简体   繁体   English

如何将单列 Pandas DataFrame 转换为 Series

[英]How to convert a single column Pandas DataFrame into Series

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?正确的做法是什么?

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

Try swapping the indices in the brackets:尝试交换括号中的索引:

df.iloc[:,0]

This should work.这应该有效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM