本文介绍了具有X,Y坐标的Pandas DataFrame坐标为NumPy矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有X
,Y
和value
列的DataFrame,例如:
I have a DataFrame with columns X
, Y
and value
, e.g.:
X | Y | value
------------------
1 | 1 | 56
2 | 1 | 13
3 | 1 | 25
... | ... | ...
1 | 2 | 7
2 | 2 | 18
... | ... | ...
1 | 123 | 91
... | ... | ...
50 | 123 | 32
我需要将其转换为DataFrame到NumPy矩阵:
I need to convert this to DataFrame to a NumPy matrix:
[[56, 13, 25, ...],
[ 7, 18, ...],
...,
[ 91, ... , 32]]
我知道我可以遍历DataFrame的每个单元,但这太慢了.有效的方法是什么?
I know I can iterate over each cell of the DataFrame, but that is too slow. What is the effective way of doing this?
还请注意:缺少DataFrame中某些坐标的值
Also note: values for some coordinates in DataFrame are missing
推荐答案
枢纽数据框,并且值应该是您所需要的:
Pivot the data frame and the values should be what you need:
df.pivot('Y', 'X', 'value').values
#array([[ 56., 13., 25., nan],
# [ 7., 18., nan, nan],
# [ 91., nan, nan, 32.]])
这篇关于具有X,Y坐标的Pandas DataFrame坐标为NumPy矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!