📌  相关文章
📜  将 NumPy 数组转换为带有标题的 Pandas 数据帧

📅  最后修改于: 2022-05-13 01:54:27.056000             🧑  作者: Mango

将 NumPy 数组转换为带有标题的 Pandas 数据帧

要将 numpy 数组转换为 Pandas 数据帧,我们使用Python Pandas 库的pandas.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

输出:

numpy-array-to-dataframe-1

示例 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

输出:

numpy-araay-to-dataframe-2

示例 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

输出:

numpy-array-to-dataframe-3