我尝试过:
x=pandas.DataFrame(...)
s = x.take([0], axis=1)
并且s
获得的是DataFrame,而不是Series。
>>> 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
已经被弃用,不再使用。请使用loc
或iloc
代替。参见关于本问题的评论和其他答案。
df.iloc
。In [7]: df.iloc[:,0]
Out[7]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
您可以通过以下代码将第一列作为Series获取:
x[x.columns[0]]
x[x.columns[x.columns.size-1]]
- fujianjin6471这不是最简单的方式吗?
按列名排序:
In [20]: df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
In [21]: df
Out[21]:
x y
0 1 4
1 2 5
2 3 6
3 4 7
In [23]: df.x
Out[23]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
In [24]: type(df.x)
Out[24]:
pandas.core.series.Series
df.x
这样访问列并不是通用的。如果列名包含空格怎么办?如果列名与DataFrame
的属性名相同怎么办?使用__getitem__
更通用(即像这样:df["x"]
)来访问列。 - ponadto当你想从CSV文件中加载一系列数据时,这个方法非常有效。
x = pd.read_csv('x.csv', index_col=False, names=['x'],header=None).iloc[:,0]
print(type(x))
print(x.head(10))
<class 'pandas.core.series.Series'>
0 110.96
1 119.40
2 135.89
3 152.32
4 192.91
5 177.20
6 181.16
7 177.30
8 200.13
9 235.41
Name: x, dtype: float64
df[df.columns[i]]
其中i
表示列的位置/编号(从0开始)。
因此,i = 0
表示第一列。
你也可以使用i = -1
来获取最后一列。
.iloc
。到了2016年,正确的答案应该是Jeff的(毕竟他是pandas
之神,你知道的; -))。我不确定SO关于由于API更改更新答案的政策是什么;我对这个答案获得的票数感到惊讶,没想到它对人们那么有用... - herrfzix
在0.20版本中已被弃用。 - ayhanix
不应再被使用,应该使用iloc
替代:s = df.ix[:,0]
。参考这篇文章比较iloc
和ix
。 - normanius