简体   繁体   English

如何防止熊猫仅将一个 df 的值分配给另一列的另一行?

[英]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:我有一个 df 看起来像这样:

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: old_df:

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

Pandas series assignment works by index . Pandas 系列分配按索引工作 Since old_df only contains index 0 , only index 0 , ie the first row, of df is updated.由于old_df仅包含索引0 ,因此仅更新索引0 ,即df的第一行。

For your particular problem, you can use iat and assign a scalar to a series:对于您的特定问题,您可以使用iat并为一系列分配标量:

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

This works because Pandas broadcasts scalars to the whole series irrespective of index.这是有效的,因为 Pandas 将标量广播到整个系列而不考虑索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅从pandas df保存非空条目值和列号,每行仅一个非空值 - Saving only non-null entry value and column number from pandas df with only one non-null value per row pandas 仅将新值从一个 df 插入到另一个有条件的 - pandas insert only new values from one df to another with conditions 仅用一行从 pandas df 获取值 - Get value from pandas df with only one line 如何通过 pandas 将特定列从一个 df 复制/粘贴到另一个 - How to copy/paste particular column from one df to another by pandas Python / Pandas:如果有匹配项,则将值从一个df添加到另一df的行末 - Python/Pandas: add value from one df to end of row in another df if there is a match append 如果 pandas 中没有重复,则从一个 df 到另一个的行值 - append row values from one df to another if no duplicates in pandas pandas df 迭代一个 df 列 qty 并以 fifo 为基础从另一个 df 列分配 qty - pandas df iterate over one df column qty and allocate qty from another df column with fifo basis Pandas,从 df 创建字典,用一列替换另一列 - Pandas, create dictionary from df, with one column as replacing another 如何将列名从一个 df 索引到另一个 df 系列? - How to index column names from one df to another df series? 使用 Python Pandas,仅当“nan”值不存在时,我可以根据另一列替换 df 中一列的值吗? - Using Python Pandas, can I replace values of one column in a df based on another column only when a "nan" value does not exist?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM