[英]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.