简体   繁体   English

比较数据框中的两列,如果值不同,则从另一列给出特定值

[英]Compare two columns in a data frame and give specific value from another column if the values aren't same

例子

I want to compare column_3 to column_1.我想将 column_3 与 column_1 进行比较。 If the value is the same give the value from column_2 back, if not search for the same value in column_1 and give the value from column_2.如果值相同,则返回 column_2 中的值,如果不相同,则在 column_1 中搜索相同的值并返回 column_2 中的值。 The output should be like column_4.输出应该类似于 column_4。

Thank you for your help!感谢您的帮助!

You could apply a Series map function to column_3 using a dictionary with keys from column_1 and corresponding values in column_2 .您可以使用带有column_3中的键和column_1相应值的字典将 Series 映射函数应用于column_2 This will then act as a lookup for values in column_3 and create a new column, column_4 :这将作为对column_3值的查找并创建一个新列column_4

import pandas as pd

df = pd.DataFrame({'column_1':[5,6,7,8,9], 
                   'column_2':[435,345,765,876,987], 
                   'column_3':[5,6,7,5,6]})

df['column_4'] = df['column_3'].map({k:v for k,v in zip(df['column_1'],df['column_2'])})


#    column_1   column_2    column_3    column_4
# 0    5          435          5          435
# 1    6          345          6          345
# 2    7          765          7          765
# 3    8          876          5          435
# 4    9          987          6          345

暂无
暂无

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

相关问题 仅当另一列值为 True 时才比较两列或多列值 - Compare two or more columns values only if another column value is True 比较两列数据框中的值 - compare values in two columns of data frame 将一个数据帧中的零值列替换为另一个数据帧中的同名列的平均值 - Replace zero valued columns in one data frame with mean values of same name column in another data frame Python:比较数据框中具有相同 id 的值并创建一个新列以指示它匹配的值列 - Python: compare values with same ids in the data frame and create a new column to indicate which value column it matched 如何比较两个不同数据框中的列并保留第一个数据框中的值? - How to compare columns from two different Data Frames and keep the values from the first Data Frame? 使用两个条件比较来自两个不同数据框的两列 - Compare two columns from two different data frame with two conditions 如何在特定列中找到最大值并在数据框的另一列中返回相应值? - How do I find the maximum value in specific columns and return the corresponding value in another column of my data frame? 如何从匹配 2 列的另一个数据框中更新数据框的列值? - How to update column value of a data frame from another data frame matching 2 columns? 将数据框的两个日期列与 python 中第二个数据框的另外两个数据框进行比较 - compare a two date columns of a data frame with another two data frames of second data frame in python 保留数据框中的行,对于某些列的值的所有组合,在另一列中包含相同的元素 - Keep rows in data frame that, for all combinations of the values of certain columns, contain the same elements in another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM