简体   繁体   English

如何根据 Pandas 中的第三列将值从一列复制到另一列?

[英]How to copy a value from one column to another based on a third column in Pandas?

So I have a sample dataframe below:所以我在下面有一个示例数据框:

   A  B     C D
0  1  2   Red  
1  4  5  Blue  
2  7  8   Red  

Output输出

   A  B     C  D
0  1  2   Red  1
1  4  5  Blue  5
2  7  8   Red  7

I am trying to fill column D using a value from either column A or B depending on what is in C?我正在尝试使用 A 列或 B 列中的值填充 D 列,具体取决于 C 中的内容?

So for example, if for the first row, since C = Red, I want to fill D with what is in A. If C = Blue, I want to fill in D with what is in B.例如,如果对于第一行,由于 C = Red,我想用 A 中的内容填充 D。如果 C = Blue,我想用 B 中的内容填充 D。

df.loc[df['C'] == 'Red', 'D'] =   df['A']
df.loc[df['C'] == 'Blue', 'D'] =  df['B']

I think I've got the left assignments down, but struggling what to do on the right to reference the same row.我想我已经完成了左边的任务,但正在努力在右边做些什么来引用同一行。 Trying to avoid looping through manually and doing this somewhat efficiently.试图避免手动循环并在某种程度上有效地执行此操作。

One way is to use np.where .一种方法是使用np.where

df['D'] = np.where(df.C == 'red', df.A, df.B)

Output输出

   A  B     C  D
0  1  2   red  1
1  4  5  blue  5
2  7  6   red  7

The way you have it set up will loop automatically.您设置的方式将自动循环。 df.loc[df['C'] == 'Red', 'D'] = df['A'] will loop through every row. df.loc[df['C'] == 'Red', 'D'] = df['A'] 将遍历每一行。 You have written this efficiently.你写得很有效率。

暂无
暂无

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

相关问题 Pandas 基于非恒定值的第三列将值从一列复制到另一列 - Pandas copy value from one column to another based on a value third column that is not constant 根据 Pandas 中的 id 将列值从一个数据帧复制到另一个数据帧 - Copy column value from one dataframe to another based on id in Pandas 根据条件将值从一列复制到另一列(使用熊猫) - Copy value from one column to another based on condition (using pandas) 如何使用 pandas 根据第三列中的值创建一个包含来自一列或另一列的值的新列? - How do I create a new column with values from one column or another based on the value in a third column using pandas? 如何根据条件将 Pandas 中的列从一个数据集复制到另一个数据集 - How to copy a column in Pandas from one dataset to another based on condition 如何在熊猫中将特定值从一列复制到另一列 - How to copy specific value from one column to another in pandas 根据另一列的值复制一列的值 - Copy value from one column based on the value of another column 如何根据 pandas 中两个不同列的条件将值从一列复制到另一列? - how to copy values from one column into another column based on conditions of two different columns in pandas? 根据 Pandas 中的列值将内容从一个 Dataframe 复制到另一个 Dataframe - Copy contents from one Dataframe to another based on column values in Pandas pandas - 有没有办法根据条件将值从一个 dataframe 列复制到另一个列? - pandas - Is there a way to copy a value from one dataframe column to another based on a condition?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM