将NumPy数组转换为带头文件的Pandas数据框架
为了将numpy数组转换为pandas数据帧,我们使用Python Pandas库的pandas.DataFrame()函数。
语法: pandas.DataFrame(data=None, index=None, columns=None)
参数:
data: numpy ndarray, dict 或 dataframe
index: 产生的数据框架的索引
columns:结果数据框架的列标签
例子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
输出: