我一直在为这个简单的事情伤透脑筋。我们可以使用 .loc
将单个值分配给多个列。但如何使用同一个数组分配多个列。
我可以做到这一点。假设我们有一个数据框 df
,我希望用数组 arr
替换其中的一些列:
df=pd.DataFrame({'a':[random.randint(1,25) for i in range(5)],'b':[random.randint(1,25) for i in range(5)],'c':[random.randint(1,25) for i in range(5)]})
>>df
a b c
0 14 8 5
1 10 25 9
2 14 14 8
3 10 6 7
4 4 18 2
arr = [i for i in range(5)]
#Suppose if I wish to replace columns `a` and `b` with array `arr`
df['a'],df['b']=[arr for j in range(2)]
Desired output:
a b c
0 0 0 16
1 1 1 10
2 2 2 1
3 3 3 20
4 4 4 11
或者我也可以在循环赋值中执行此操作。但是有没有更有效的方法而不需要重复或循环呢?
最佳答案
让我们尝试一下 assign
:
cols = ['a', 'b']
df.assign(**dict.fromkeys(cols, arr))
a b c
0 0 0 5
1 1 1 9
2 2 2 8
3 3 3 7
4 4 4 2
关于python-3.x - 使用同一数组重新分配多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65475162/