Python-如何将pandas系列或索引转换为Numpy数组?
发布于 2021-02-02 23:13:49
你是否知道如何以NumPy数组或python列表的形式获取DataFrame的索引或列?
关注者
0
被浏览
172
1 个回答
-
要获取NumPy数组,应使用以下
values
属性: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)
这样可以访问数据的存储方式,因此无需进行转换。
注意:此属性也可用于其他许多熊猫的对象。In [3]: df['A'].values Out[3]: Out[16]: array([1, 2, 3])
要将索引作为列表获取,请致电tolist:
In [4]: df.index.tolist() Out[4]: ['a', 'b', 'c']
同样,对于列。