【发布时间】:2023-03-02 23:31:01
【问题描述】:
我试过了:
x=pandas.DataFrame(...)
s = x.take([0], axis=1)
s 得到一个 DataFrame,而不是一个系列。
【问题讨论】:
标签: python dataframe pandas series
我试过了:
x=pandas.DataFrame(...)
s = x.take([0], axis=1)
s 得到一个 DataFrame,而不是一个系列。
【问题讨论】:
标签: python dataframe pandas 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 在 pandas 0.20.2 中已被弃用,所以不要使用它。请改用loc 或iloc。请参阅 cmets 和此问题的其他答案。
【讨论】:
df.set_index('x').y
.iloc。 2016 年,正确答案是 Jeff 的(毕竟他是 pandas上帝,请注意 ;-))。由于 API 更改,我不确定 SO 关于更新答案的政策是什么;老实说,我对这个答案的投票数感到惊讶,认为它对人们没有那么有用......
ix 在 0.20 版本中是 deprecated。
ix 不应再使用,请改用iloc:s = df.ix[:,0]。有关iloc 和ix 的比较,请参阅this post。
从 v0.11+,... 使用 df.iloc。
In [7]: df.iloc[:,0]
Out[7]:
0 1
1 2
2 3
3 4
Name: x, dtype: int64
【讨论】:
您可以通过以下代码将第一列作为一个系列:
x[x.columns[0]]
【讨论】:
x[x.columns[x.columns.size-1]]
这不是最简单的方法吗?
按列名:
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-s 属性名重合怎么办?使用__getitem__ 访问列更为通用(例如:df["x"])。
当您想从 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获取最后一列
【讨论】: