Reassigning multiple columns with same array

Viewed 66

I've been breaking my head over this simple thing. Ik we can assign a single value to multiple columns using .loc. But how to assign multiple columns with the same array.

Ik I can do this. Let's say we have a dataframe df in which I wish to replace some columns with the array 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

Or I can also do this in a loopwise assignment. But is there a more efficient way without repetition or loops?

2 Answers

Let's try with 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

I did an assign statement df.a = df.b = 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)]})

arr = [i for i in range(5)]

df
    a   b   c
0   2   8  18
1  17  15  25
2   6   5  17
3  12  15  25
4  10  10   6

df.a = df.b = arr
df

   a  b   c
0  0  0  18
1  1  1  25
2  2  2  17
3  3  3  25
4  4  4   6
Related