Pandas和NumPy是Python数据科学生态系统的基石。Pandas凭借其DataFrame结构擅长数据操作,而NumPy凭借其数组在高效数值计算方面表现出色。通常,您需要在这两个库之间无缝转换,将Pandas DataFrame转换为NumPy数组以进行进一步分析或处理。本文详细介绍了这种转换最有效的方法。
目录
to_numpy()
方法:推荐方法
to_numpy()
方法是将Pandas DataFrame转换为NumPy数组最直接、最有效的方法。它直接将DataFrame的值转换为NumPy数组,并提供指定数据类型的灵活性。
import pandas as pd
import numpy as np
# 示例DataFrame
data = {'col1': [1, 2, 3], 'col2': [4, 5, 6], 'col3': [7.1, 8.2, 9.3]}
df = pd.DataFrame(data)
# 转换为NumPy数组
numpy_array = df.to_numpy()
print("默认dtype:n", numpy_array)
# 指定dtype
numpy_array_float = df.to_numpy(dtype=np.float64)
print("nFloat64 dtype:n", numpy_array_float)
numpy_array_int = df.to_numpy(dtype=np.int32)
print("nInt32 dtype (浮点数将被截断):n", numpy_array_int)
请注意,指定dtype
如何允许精确控制输出数组的类型。如果省略,to_numpy()
会根据DataFrame的数据智能地推断最合适的类型。
.values
属性:传统方法
.values
属性也产生DataFrame数据的NumPy数组表示。虽然功能上与to_numpy()
类似,但它被认为是一种传统方法。to_numpy()
因其清晰性和明确性而更受青睐。
import pandas as pd
import numpy as np
# 示例DataFrame
data = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data)
# 使用.values转换
numpy_array = df.values
print(numpy_array)
输出与使用to_numpy()
相同,但to_numpy()
是更现代化和推荐的做法。
to_records()
方法:创建结构化数组
当您需要一个具有命名字段(类似于结构化数组)的NumPy数组时,请使用to_records()
方法。它将DataFrame转换为NumPy记录数组,其中每一列都成为一个命名字段。
import pandas as pd
import numpy as np
# 示例DataFrame
data = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data)
# 转换为NumPy记录数组
numpy_record_array = df.to_records()
print(numpy_record_array)
print("n记录数组的数据类型:")
print(numpy_record_array.dtype)
请注意记录数组中包含索引。当在NumPy数组结构中保留列名对于后续分析至关重要时,此方法尤其有用。
总之,to_numpy()
是推荐用于一般DataFrame到NumPy数组转换的方法。.values
提供功能上等效的替代方案,而to_records()
最适合需要命名字段的结构化数组。最佳选择取决于特定需求和所需NumPy数组的结构。