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

Linda Hamilton
发布: 2024-10-20 15:48:29
原创
835 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!