可能是一个非常简单的问题,但我想不出解决方案。 我有一个包含 9 列和 ~100000 行的数据框。数据是从图像中提取的,因此两列(“行”和“列”)指的是数据的像素位置。我如何创建一个 numpy 数组 A 使得行和列指向另一列中的另一个数据条目,例如“脾气暴躁”?
A[row, col]
# 0.1232
我想避免 for 循环或类似的东西。
最佳答案
你可以这样做 -
# Extract row and column information
rowIDs = df['row']
colIDs = df['col']
# Setup image array and set values into it from "grumpiness" column
A = np.zeros((rowIDs.max()+1,colIDs.max()+1))
A[rowIDs,colIDs] = df['grumpiness']
sample 运行-
>>> df
row col grumpiness
0 5 0 0.846412
1 0 1 0.703981
2 3 1 0.212358
3 0 2 0.101585
4 5 1 0.424694
5 5 2 0.473286
>>> A
array([[ 0. , 0.70398113, 0.10158488],
[ 0. , 0. , 0. ],
[ 0. , 0. , 0. ],
[ 0. , 0.21235838, 0. ],
[ 0. , 0. , 0. ],
[ 0.84641194, 0.42469369, 0.47328598]])
关于python - 从 Pandas 数据框创建二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33753323/