pandas 如何从熊猫中的两列创建一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43160575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:19:38  来源:igfitidea点击:

How to create an array from two columns in pandas

pythonarrayspandas

提问by Clement Attlee

suppose I have a DataFrame similar to this:

假设我有一个与此类似的 DataFrame:

d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

   col1  col2  col3
0     0     1     2
1     2     3     4
2     4     5     8

How can I select col1 and col2 and turn them into this array?

如何选择 col1 和 col2 并将它们转换为这个数组?

array([[0, 1],
       [2, 3],
       [4, 5]])

回答by ayhan

You can access the underlying numpy array via the to_numpymethod:

您可以通过以下to_numpy方法访问底层的 numpy 数组:

df[['col1', 'col2']].to_numpy()
Out: 
array([[0, 1],
       [2, 3],
       [4, 5]])


.valuesattribute will do the same if you are on an earlier version (before v0.24).

.values如果您使用的是早期版本(v0.24 之前),则属性将执行相同的操作。

回答by Mohammad Akhtar

You can also achieve the same output with the below code.

您还可以使用以下代码实现相同的输出。

import numpy as np
np.array(df[['col1','col2']])
Out[60]: 
array([[0, 1],
       [2, 3],
       [4, 5]])