如何将numpy数组列表转为Pandas DataFrame?解决二维输入报错问题
The error you're seeing happens because each element in your list_arrays is a 2D NumPy array (shape (1,9)), and pd.DataFrame() expects either a 2D array directly, or a list of 1D sequences (like 1D arrays or lists) to represent rows. When you pass a list of 2D arrays, pandas can't interpret them as valid row inputs, hence the ValueError: Must pass 2-d input.
Here are a few straightforward fixes:
1. Extract the 1D row from each 2D array
Since each array in your list is a single row wrapped in an extra dimension, you can simply index the first (and only) row of each array to get a 1D array, then pass that list to pd.DataFrame:
import pandas as pd import numpy as np list_arrays = [np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0]], dtype='uint8'), np.array([[0, 0, 3, 2, 0, 0, 0, 0, 0]], dtype='uint8')] # Extract the first row of each 2D array d = pd.DataFrame([arr[0] for arr in list_arrays])
Alternatively, use flatten() to remove the extra dimension:
d = pd.DataFrame([arr.flatten() for arr in list_arrays])
2. Concatenate all arrays into a single 2D array first
Another approach is to combine all your 2D arrays into one large 2D array using np.concatenate, then feed that directly to pd.DataFrame:
# Concatenate along the row axis (axis=0) combined_array = np.concatenate(list_arrays, axis=0) d = pd.DataFrame(combined_array)
Both methods will produce a DataFrame with each original array as a row, resulting in a shape of (2,9) (2 rows, 9 columns).
内容的提问来源于stack exchange,提问作者Marcos Santana

