将 NumPy 数组转换为带有标题的 Pandas 数据帧
要将 numpy 数组转换为 Pandas 数据帧,我们使用Python Pandas 库的pandas.DataFrame()函数。
Syntax: pandas.DataFrame(data=None, index=None, columns=None)
Parameters:
data: numpy ndarray, dict or dataframe
index: index for resulting dataframe
columns: column labels for resulting dataframe
示例 1:
import numpy as np
import pandas as pd
arr = np.random.rand(4, 3)
print("Numpy array:")
print(arr)
# convert numpy array to dataframe
df = pd.DataFrame(arr, columns =['A', 'B', 'C'])
print("\nPandas DataFrame: ")
df
输出:
示例 2:
import numpy as np
import pandas as pd
arr = np.random.rand(6).reshape(2, 3)
print("Numpy array:")
print(arr)
# convert numpy array to dataframe
df = pd.DataFrame(arr, columns =['C1', 'C2', 'C3'])
print("\nPandas DataFrame: ")
df
输出:
示例 3:
import numpy as np
import pandas as pd
arr = np.array([[1, 2], [4, 5]])
print("Numpy array:")
print(arr)
# convert numpy array to dataframe
df = pd.DataFrame(data = arr, index =["row1", "row2"],
columns =["col1", "col2"])
print("\nPandas DataFrame: ")
df
输出: