如何将 pandas 系列或索引转换为 Numpy 数组? [英] How do I convert a pandas Series or index to a Numpy array?

查看:49
本文介绍了如何将 pandas 系列或索引转换为 Numpy 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道如何将 DataFrame 的索引或列作为 NumPy 数组或 Python 列表获取吗?

Do you know how to get the index or column of a DataFrame as a NumPy array or python list?

推荐答案

要获得 NumPy 数组,您应该使用 values 属性:

To get a NumPy array, you should use the values attribute:

In [1]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']); df
   A  B
a  1  4
b  2  5
c  3  6

In [2]: df.index.values
Out[2]: array(['a', 'b', 'c'], dtype=object)

这会访问数据的存储方式,因此无需进行转换.
注意:此属性也可用于许多其他 Pandas 的对象.

In [3]: df['A'].values
Out[3]: Out[16]: array([1, 2, 3])

<小时>

要以列表形式获取索引,请调用tolist:

In [4]: df.index.tolist()
Out[4]: ['a', 'b', 'c']

同样,对于列.

这篇关于如何将 pandas 系列或索引转换为 Numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆