如何将 pandas 系列或索引转换为Numpy数组? [英] How do I convert a pandas Series or index to a Numpy array?
本文介绍了如何将 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)
这将访问如何存储数据,因此无需进行转换.
注意:此属性也可用于其他许多熊猫的对象.
This accesses how the data is already stored, so there's no need for a conversion.
Note: This attribute is also available for many other pandas' objects.
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屋!
查看全文