[英]How to convert a single column Pandas DataFrame into Series
我有以下数据框:
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
正确的做法是什么?
s = df.squeeze()
>>> s
gene
foo 4
bar 3
Name: score, dtype: float64
要将其恢复为数据帧:
>>> s.to_frame()
score
gene
foo 4
bar 3
尝试交换括号中的索引:
df.iloc[:,0]
这应该有效。
交换索引可以轻松解决问题:
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.