如何将pandas DataFrame的第一列作为Series?
我试过:
x=pandas.DataFrame(...)
s = x.take([0], axis=1)
结果发现,s
得到的是一个数据框(DataFrame),而不是一个序列(Series)。
6 个回答
124
你可以通过下面的代码获取第一列的数据,结果会是一个序列(Series):
x[x.columns[0]]
156
从版本0.11开始,... 使用 df.iloc
。
In [7]: df.iloc[:,0]
Out[7]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
154
>>> import pandas as pd
>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
>>> df
x y
0 1 4
1 2 5
2 3 6
3 4 7
>>> s = df.ix[:,0]
>>> type(s)
<class 'pandas.core.series.Series'>
>>>
===========================================================================
更新
如果你是在2017年6月之后看到这段话,ix
在pandas 0.20.2版本中已经被淘汰了,所以不要再使用它了。你可以用loc
或者iloc
来代替。可以查看这个问题的评论和其他回答。