# 将 NumPy 数组转换为 Pandas DataFrame

## 使用 `pandas.DataFrame()` 方法将 NumPy 数组转换为 Pandas DataFrame

``````from numpy import random
import pandas as pd

random.seed(5)
random.randint(100, size=(3, 5))
data_array = random.randint(100, size=(4, 3))

print("NumPy Data Array is:")
print(data_array)

print("")

data_df = pd.DataFrame(data_array)
print("The DataFrame generated from the NumPy array is:")
print(data_df)
``````

``````NumPy Data Array is:
[[27 44 77]
[75 65 47]
[30 84 86]
[18  9 41]]

The DataFrame generated from the NumPy array is:
0   1   2
0  27  44  77
1  75  65  47
2  30  84  86
3  18   9  41
``````

``````from numpy import random
import pandas as pd

random.seed(5)
random.randint(100, size=(3, 5))
data_array = random.randint(100, size=(4, 3))
row_indices = ["Row_1", "Row_2", "Row_3", "Row_4"]
column_names = ["Column_1", "Column_2", "Column_3"]

print("NumPy Data Array is:")
print(data_array)

print("")

data_df = pd.DataFrame(data_array, index=row_indices, columns=column_names)
print("The DataFrame generated from the NumPy array is:")
print(data_df)
``````

``````NumPy Data Array is:
[[27 44 77]
[75 65 47]
[30 84 86]
[18  9 41]]

The DataFrame generated from the NumPy array is:
Column_1  Column_2  Column_3
Row_1        27        44        77
Row_2        75        65        47
Row_3        30        84        86
Row_4        18         9        41
``````

``````import numpy as np
import pandas as pd

marks_array = np.array([['', 'Mathematics', 'Economics'],
['Sunny', 25, 23],
['Alice', 23, 24]])

print("NumPy Data Array is:")
print(marks_array)

print("")

row_indices = marks_array[1:, 0]
column_names = marks_array[0, 1:]
data_df = pd.DataFrame(
data=np.int_(marks_array[1:, 1:]), index=row_indices, columns=column_names)

print("The DataFrame generated from the NumPy array is:")
print(data_df)
``````

``````NumPy Data Array is:
[['' 'Mathematics' 'Economics']
['Sunny' '25' '23']
['Alice' '23' '24']]

The DataFrame generated from the NumPy array is:
Mathematics  Economics
Sunny           25         23
Alice           23         24
``````

`numpy.array()` 在制作 NumPy 数组的同时，将整数值转换为字符串值，以保证数组的数据格式相同。我们使用 `numpy.int_()` 函数将数据值转换回整数类型。

## 相关文章 - Pandas DataFrame

• 如何将 Pandas DataFrame 列标题获取为列表
• 如何删除 Pandas DataFrame 列
• 如何在 Pandas 中将 DataFrame 列转换为日期时间
• 如何在 Pandas DataFrame 中将浮点数转换为整数