将 Pandas Dataframe 转换为 numpy 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55148750/
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 06:20:46  来源:igfitidea点击:

Converting Pandas Dataframe to numpy array

pythonpandasnumpy

提问by TLanni

The following is a Pandas dataframe df

以下是 Pandas 数据框 df

index_column      value_column
 0                   20
 2                   28
 1                   30

It needs to be converted into a numpy array where index_columnbecomes the index of numpy array and value_columnbecomes the corresponding value.

它需要转换成一个numpy数组,其中index_column成为numpy数组的索引并value_column成为相应的值。

That is np_arr[0]=20, np_arr[1]=30, np_arr[2]=28and so on.

np_arr[0]=20, np_arr[1]=30,np_arr[2]=28等等。

How can this be achieved?

如何做到这一点?

回答by Ashish kulkarni

np_arr = df.value_column.values

回答by Serge Ballesta

Pandas internally uses np.arrays. The valuesattribute is all you need:

Pandas 在内部使用np.arrays. 该values属性是所有您需要:

df.value_column.values

is the np.arraythat you want.

np.array你想要的。

回答by sourebh_s

np_arr = df.value_column.values

np_arr = df.value_column.values

if your column name has special characters like space, use the following:

如果您的列名包含空格等特殊字符,请使用以下内容:

np_arr = df['temperature [Celsius]'].values

np_arr = df['temperature [Celsius]'].values