Python 如何将 Pandas 单列数据框转换为系列或 numpy 向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33385238/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:16:42  来源:igfitidea点击:

How to convert pandas single column data frame to series or numpy vector

pythonpandas

提问by neversaint

I have the following data frame just single column.

我有以下数据框,只有单列。

import pandas as pd
tdf =  pd.DataFrame({'s1' : [0,1,23.4,10,23]})

Currently it has the following shape.

目前它具有以下形状。

In [54]: tdf.shape
Out[54]: (5, 1)

How can I convert it to a Series or a numpy vector so that the shape is simply (5,)

如何将其转换为系列或 numpy 向量,以便形状简单 (5,)

采纳答案by Anand S Kumar

You can simply index the series you want. Example -

您可以简单地索引您想要的系列。例子 -

tdf['s1']

Demo -

演示 -

In [24]: tdf =  pd.DataFrame({'s1' : [0,1,23.4,10,23]})

In [25]: tdf['s1']
Out[25]:
0     0.0
1     1.0
2    23.4
3    10.0
4    23.0
Name: s1, dtype: float64

In [26]: tdf['s1'].shape
Out[26]: (5,)

If you want the values in the series as numpy array, you can use .valuesaccessor , Example -

如果您希望系列中的值作为 numpy 数组,您可以使用.valuesaccessor ,例如 -

In [27]: tdf['s1'].values
Out[27]: array([  0. ,   1. ,  23.4,  10. ,  23. ])