【问题标题】:How to get the difference of 2 lists in a Pandas DataFrame?如何在 Pandas DataFrame 中获取 2 个列表的差异?
【发布时间】:2019-07-11 10:04:43
【问题描述】:

我是 python Pandas 的新手。我遇到了一个问题,要在 Pandas DataFrame 中找到 2 个列表的差异。

带有; 分隔符的示例输入:

ColA; ColB  
A,B,C,D; B,C,D  
A,C,E,F; A,C,F  

预期输出:

ColA; ColB; ColC  
A,B,C,D; B,C,D; A  
A,C,E,F; A,C,F; E  

我想做的类似于:

df['ColC'] = np.setdiff1d(df['ColA'].str.split(','), df['ColB'].str.split(','))

但它返回一个错误:

raise ValueError('值的长度与索引的长度不匹配',data,index,len(data),len(index))

请多多指教

【问题讨论】:

  • 嗨,你想要 [A,B,C,D] - [B,C,D] = [A]?如果是这种情况,那么“result = list((Counter(L1) - Counter(L2)).elements())”应该可以完成这项工作
  • 你如何阅读你的文件?你能给我看看那部分吗?

标签: python python-3.x pandas list dataframe


【解决方案1】:

您可以在 DataFrame 上应用 lambda 函数来找出不同之处,如下所示:

import pandas as pd

# creating DataFrame (can also be loaded from a file)
df = pd.DataFrame([[['A','B','C','D'], ['B','C']]], columns=['ColA','ColB'])

# apply a lambda function to get the difference
df['ColC'] = df[['ColA','ColB']].apply(lambda x: [i for i in x[0] if i not in x[1]], axis=1)

请注意!这将找到不对称差异 ColA - ColB

结果:

【讨论】:

  • 非常感谢,它完美运行,拯救了我的一天!作为初学者,我想我需要努力学习如何使用应用或转换。
猜你喜欢
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
相关资源
最近更新 更多