【发布时间】:2021-05-29 16:45:59
【问题描述】:
我的问题与 cs95 在这篇文章中的出色回答有关:
Convert pandas dataframe to NumPy array
它提供了一种将 pandas DataFrame 转换为 numpy-matrix 的快速简便的方法。希望您原谅我直接引用他的设置:
df = pd.DataFrame(data={'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]},
index=['a', 'b', 'c'])
# Convert the entire DataFrame
df.to_numpy()
# array([[1, 4, 7],
# [2, 5, 8],
# [3, 6, 9]])
# Convert specific columns
df[['A', 'C']].to_numpy()
# array([[1, 7],
# [2, 8],
# [3, 9]])
我需要将 DataFrames columns 转换为 numpy-array。在他的回答中,我们得到的是一个带有 rows 的数组。
我希望能够得到这样的东西
columns = df.other_to_numpy()
#array([[1,2,3],
# [4,5,6],
# [7,8,9]])
因为这允许我将原始列作为columns[0] 引用到columns[2]。我意识到这个问题与我所引用的帖子非常接近,但在对上述帖子的回答中,我找不到这个问题变体的答案。如果这是一个非常简单的问题,请您耐心等待。
【问题讨论】:
-
简单地转置数据帧。试试
df.T.to_numpy()或df.to_numpy().T
标签: python arrays pandas dataframe numpy