【问题标题】:Comparing two cell values and extracting the difference比较两个单元格值并提取差异
【发布时间】:2021-04-20 15:07:27
【问题描述】:

试图比较两个单元格的值。对于每个主题,我需要筛选旧国家和新国家列表是否完全相同,或者是否在新国家列表中添加或删除了新国家,然后我想要第三列来标识已添加或删除的国家。

【问题讨论】:

  • 如果数据可以以文本、csv 或表格的形式提供,将会非常有帮助
  • 对此SO question 的回答将非常有助于回答问题!

标签: python pandas


【解决方案1】:

这是一个工作示例(针对您的一个请求)。您可以更改func 以实现您想要的任何东西。照原样,它获取第 2 列中不在第 1 列中的元素。

import pandas as pd

# some data that is in the same format as your image
df = pd.DataFrame()
df['Col1'] = ['A;E;I;O;U']
df['Col2'] = ['A;B;C;D;E']

# function to find the differences between two sets
def func(string1,string2):
    string1_split = string1.split(';')
    string2_split = string2.split(';')
    return [x for x in set(string2_split) if x not in set(string1_split)]

# apply the function to the two columns
df['Col3'] = df.apply(lambda x: func(x['Col1'], x['Col2']), axis=1)

df[Col3] 输出:

['B','C','D']

【讨论】:

  • 这也为问题提供MCVE!不错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多