我正尝试使用numpy将值分配给数组中特定行子集的某些列,如下所示:
import numpy as np
test = np.zeros((10, 5))
rows = [0, 2, 4, 6, 9]
cols = [1, 2, 3]
proportions = [0.2, 0.3, 0.4]
test[rows, cols] = proportions
但是,这将返回错误:
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (5,) (3,)
当我尝试在Pandas中执行相同的操作时,它确实起作用:
import pandas as pd
test_df = pd.DataFrame(test)
test_df.iloc[rows, cols] = proportions
print(test_df)
0 1 2 3 4
0 0.0 0.2 0.3 0.4 0.0
1 0.0 0.0 0.0 0.0 0.0
2 0.0 0.2 0.3 0.4 0.0
3 0.0 0.0 0.0 0.0 0.0
4 0.0 0.2 0.3 0.4 0.0
5 0.0 0.0 0.0 0.0 0.0
6 0.0 0.2 0.3 0.4 0.0
7 0.0 0.0 0.0 0.0 0.0
8 0.0 0.0 0.0 0.0 0.0
9 0.0 0.2 0.3 0.4 0.0
如何解决该问题并使之在numpy中工作?
答案 0 :(得分:2)
如果要使用一个数组(或多个数组)的索引作为索引,则Numpy索引的工作方式与熊猫.iloc
的索引工作方式不太相同。但是您可以使用np.ix_
test[np.ix_(rows, cols)] = proportions