假设我有一个数据框X,它以0s开头,尺寸为m x n。我在pandas.series Y中有n个唯一值(1,2,3,...,n),长度为m。如何在不使用循环的情况下有效地设置X的第i行的Y [i]列(将0更改为1)。尤其对于大m和n。
For example, for Y = [3,2,1]
X
row 1 2 3
0 0 0 0
1 0 0 0
2 0 0 0
to
row 1 2 3
0 0 0 1
1 0 1 0
2 1 0 0
答案 0 :(得分:2)
我不确定您为什么反对for循环。这应该相当有效。
for row, col in enumerate(Y):
df.iat[n, col] = 1
您还可以计算索引位置并将其值设置为1,然后将结果重塑为矩阵的m x n
形状。
Y = [3, 2, 1]
n = 5
m = len(Y)
locations = set(row * n + col for row, col in enumerate(Y))
df = pd.DataFrame(
np.array([1 if idx in locations else 0 for idx in range(m * n)]).reshape((m, n))
)
>>> df
0 1 2 3 4
0 0 0 0 1 0
1 0 0 1 0 0
2 0 1 0 0 0