简体   繁体   English

将 pandas DataFrame 列转换为 NumPy 数组(扩展问题)

[英]Convert pandas DataFrame columns to NumPy array (extension question)

My question relates to the excellent answer by cs95 in this post right here:我的问题与 cs95 在这篇文章中的出色回答有关:

Convert pandas dataframe to NumPy array 将 pandas dataframe 转换为 NumPy 数组

It gives a quick and easy method to turn a pandas DataFrame into a numpy-matrix.它提供了一种将 pandas DataFrame 转换为 numpy 矩阵的快速简便的方法。 I hope you forgive me quoting his setup directly:希望您原谅我直接引用他的设置:

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]])

What I need is to turn the DataFrames columns into a numpy-array.我需要的是把 DataFrames变成一个 numpy 数组。 In his answer what we get is an array with the rows .在他的回答中,我们得到的是一个带有rows的数组。

I would like to be able to get something like this我希望能够得到这样的东西

columns = df.other_to_numpy()
#array([[1,2,3],
#       [4,5,6],
#       [7,8,9]])

Since that would allow me to reference the original columns as columns[0] to columns[2] .因为这将允许我将原始列引用为columns[0]columns[2] I realize this question is very close to the one of the post I am referencing but in the answer to said post I could not find an answer to this variation of the question.我意识到这个问题与我所引用的帖子非常接近,但在对上述帖子的回答中,我找不到这个问题变体的答案。 Thank you for your patience if this is a very simple problem.如果这是一个非常简单的问题,感谢您的耐心等待。

You mean you want the transposed array?你的意思是你想要转置数组?

df.T.values

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM