[英]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.
试图避免手动循环并在某种程度上有效地执行此操作。
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.