user2237511
user2237511

Reputation: 1149

How to replace a whole column with an array of numbers in pandas

I searched a lot but didn't quite find what I am looking for.

I have an array of numbers say [1, 2, 3].

and I have a dataframe:

   attr1  attr2
A     10     13
B     11     14
C     12     15

I want to replace all values of attr1 with the values in the array so that my output is

   attr1   attr2
A      1      13
B      2      14
C      3      15

I tried

df['attr1'] = df['attr1'] <- array
print df['attr1']

^ - that is setting everything to True or False

and df[['attr1']] <- array throws an exception

ValueError: Wrong number of items passed 51, placement implies 1

Upvotes: 2

Views: 8522

Answers (1)

seemo
seemo

Reputation: 257

You can use a list containing the values:

df['attr1'] = [1,2,3]

Or if you have a bigger range on your dataframe use a range of values:

df['attr1'] = range(1,4)

Upvotes: 7

Related Questions