如何将pandas数据帧的第一列作为一个系列?

2024-04-19 18:07:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过:

x=pandas.DataFrame(...)
s = x.take([0], axis=1)

s得到的是数据帧,而不是序列。


Tags: 数据dataframepandas序列takeaxis
3条回答
>>> 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中被弃用,所以不要使用它。请改用lociloc。请参阅对此问题的评论和其他答案。

从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]]

相关问题 更多 >