将 pandas pd 转换为 numpy 数组并返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40972147/
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
convert pandas pd to numpy array and back
提问by Barbara Miranda
What I want is to convert a numpy array to pandas dataframe.
我想要的是将 numpy 数组转换为 Pandas 数据帧。
df.head()
A B C D
0 34 howdy cow meting
1 23 cow me howdy
After tokenizing this df
标记此 df 后
df.head()
A B C D
0 34 1 2 3
1 23 2 4 1
converted df to numpy array for analysis with KMeans numpy array
将 df 转换为 numpy 数组以使用 KMeans numpy 数组进行分析
array [[34 ,1, 2, 3],
[23 ,2, 4, 1]]
Question how can i convert this back to the first df i.e comparing the index of the array to the index of pandas and getting the row values
问题我如何将其转换回第一个 df,即比较数组的索引与Pandas的索引并获取行值
回答by jezrael
I think you can use values
for convert to numpy array
and then DataFrame
constructor:
我认为您可以使用values
for convert tonumpy array
然后DataFrame
构造函数:
arr = df.values
print (arr)
[[34 1 2 3]
[23 2 4 1]]
print (pd.DataFrame(arr))
0 1 2 3
0 34 1 2 3
1 23 2 4 1
print (pd.DataFrame(arr, index=df.index, columns=df.columns))
A B C D
0 34 1 2 3
1 23 2 4 1