简体   繁体   中英

How to prevent pandas from only assigning value from one df to column of another for only one row?

I have a df that looks like this:

id   col1     col2
1    2         3 
4    5         6
7    8         9 

when I go to add a new column and assign a value like this:

df['new_col'] = old_df['email']

The assignment only assigns the value to the first like so:

id   col1     col2   new_col
 1    2         3     a@a.com
 4    5         6     NaN
 7    8         9     NaN

How do I have the assignment for all rows like so:

id   col1     col2   new_col
 1    2         3     a@a.com
 4    5         6     a@a.com
 7    8         9     a@a.com 

edit:

old_df:

id   col3     col4   email
 1    2         3     a@a.com

Pandas series assignment works by index . Since old_df only contains index 0 , only index 0 , ie the first row, of df is updated.

For your particular problem, you can use iat and assign a scalar to a series:

df['new_col'] = old_df['email'].iat[0]

This works because Pandas broadcasts scalars to the whole series irrespective of index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM