首页  >  文章  >  后端开发  >  如何从 Pandas 索引和列中检索 NumPy 数组和 Python 列表?

如何从 Pandas 索引和列中检索 NumPy 数组和 Python 列表?

Linda Hamilton
Linda Hamilton原创
2024-10-20 15:48:29839浏览

How to Retrieve NumPy Arrays and Python Lists from Pandas Indexes and Columns?

从 Pandas 索引和列中检索 NumPy 数组

使用 Pandas 时,以 NumPy 数组或 Python 列表的形式访问索引或特定列是常见要求。以下是实现此目的的方法:

转换为 NumPy 数组

要获取 NumPy 数组,请利用 value 属性。此属性允许您检索基础数据,而无需显式转换:

<code class="python">import pandas as pd

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

# Get the index as a NumPy array
index_array = df.index.values
print(index_array) 
# Output: array(['a', 'b', 'c'], dtype=object)</code>

转换为 Python 列表

要将索引或列检索为 Python 列表,请使用 tolist()方法:

<code class="python"># Get the index as a list
index_list = df.index.tolist()
print(index_list) # Output: ['a', 'b', 'c']</code>

同样,您可以通过访问 columns 属性然后应用 tolist() 方法来获取列作为列表。

以上是如何从 Pandas 索引和列中检索 NumPy 数组和 Python 列表?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn