Python 如何将 Pandas DataFrame 的第一列作为系列获取?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15360925/
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 get the first column of a pandas DataFrame as a Series?
提问by Yariv
I tried:
我试过:
x=pandas.DataFrame(...)
s = x.take([0], axis=1)
And sgets a DataFrame, not a Series.
并s获得一个 DataFrame,而不是一个系列。
采纳答案by herrfz
>>> 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'>
>>>
===========================================================================
================================================== ==========================
UPDATE
更新
If you're reading this after June 2017, ixhas been deprecated in pandas 0.20.2, so don't use it. Use locor ilocinstead. See comments and other answers to this question.
如果您是在 2017 年 6 月之后阅读本文,ix它在 pandas 0.20.2 中已被弃用,所以不要使用它。使用loc或iloc代替。请参阅此问题的评论和其他答案。
回答by HYRY
You can get the first column as a Series by following code:
您可以通过以下代码将第一列作为系列获取:
x[x.columns[0]]
回答by Jeff
From v0.11+, ... use df.iloc.
从 v0.11+ 开始,...使用df.iloc.
In [7]: df.iloc[:,0]
Out[7]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
回答by SamJ
Isn't this the simplest way?
这不是最简单的方法吗?
By column name:
按列名:
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
回答by Christopher Pfeifer
This works great when you want to load a series from a csv file
当您想从 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

