如何将单列 Pandas DataFrame 转换为 Series
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39072010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a single column Pandas DataFrame into Series
提问by neversaint
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?
正确的做法是什么?
回答by Alexander
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
回答by honza_p
Try swapping the indices in the brackets:
尝试交换括号中的索引:
df.iloc[:,0]
This should work.
这应该有效。
回答by Aman khan Roohaani
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