vinay karagod
vinay karagod

Reputation: 254

How to add a constant value to a column in python pandas?

I am trying to pass constant values in a python pandas data frame, and it is adding the only first row and the rest of the show as NaN. I am not sure what I am doing wrong. I tried all the possible answers but it still not working for. If you guys have any idea please let me know

weekdayDistance.loc[:,'UID'] = user.UID.head(1)
weekdayDistance['UID'] = user.UID.head(1)
weekdayDistance.loc['UID'] = user.UID.loc[0]

output:
a b c UID
1 1 1  1
2 2 2  NaN
3 3 3  NaN

what I want 
a b c UID
1 1 1  1
2 2 2  1
3 3 3  1

Upvotes: 0

Views: 5054

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34086

You can do like below:

user['UID'] = 1

If just one row is getting filled, you can use ffill(). It will replicate the first row's value in all the rows.

user.UID = user.UID.ffill()

Upvotes: 1

Praveen Bushipaka
Praveen Bushipaka

Reputation: 493

Simple answer would be

df['col_name'] = 1

or you can use insert, where 0 is the index of column, followed by column name and its constant value.

df.insert(0, colname, value)

This link here might give you explanation

Upvotes: 2

Related Questions