DataFrame检查2列是否包含相同的元素
我有一个数据框,并有2列X& Y.
df = pd.DataFrame({
'X': ['a', 'a,b,c', 'a,d', 'e,f', 'a,c,d,f', 'e'],
'Y': ['a', 'a,c,b', 'd,a', 'e,g', 'a,d,f,g', 'e']
})
我想在数据框架中创建一个新列('Match'),如果列x& y具有相同的元素,然后是true否则错误。
df = pd.DataFrame({
'X': ['a', 'a,b,c', 'a,d', 'e,f', 'a,c,d,f', 'e'],
'Y': ['a', 'a,c,b', 'd,a', 'e,g', 'a,d,f,g', 'e'],
'Match':['True','True','True','False','False','True']
})
请帮助我
I have a data frame and with 2 columns X & Y.
df = pd.DataFrame({
'X': ['a', 'a,b,c', 'a,d', 'e,f', 'a,c,d,f', 'e'],
'Y': ['a', 'a,c,b', 'd,a', 'e,g', 'a,d,f,g', 'e']
})
I want to create a new column('Match') in the dataframe such if the columns X & Y have the same elements, then True else False.
df = pd.DataFrame({
'X': ['a', 'a,b,c', 'a,d', 'e,f', 'a,c,d,f', 'e'],
'Y': ['a', 'a,c,b', 'd,a', 'e,g', 'a,d,f,g', 'e'],
'Match':['True','True','True','False','False','True']
})
Kindly help me with this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这起作用:
基本上,我在这里做的是将每个数据点从每列转换为一组,然后将它们进行比较。
它应该独立于那种(例如数字或字符串)独立起作用。
但是,请注意,如果有复制,则不会有所不同。例如,如果您具有'a,c,c,b'vs'a,c,b',那将产生真实。
This works:
Basically, what I'm doing here is to convert each data point from each column into a set, and then comparing them.
It should work independently of the kind of thata (numbers or strings for example).
Notice, however, it wont differenciate if there're replicates. For example, if you have 'a,c,c,b' vs 'a,c,b', that would yield True.
您可以尝试将列拆分以列出,然后进行排序并进行比较。
或者,您可以将列表转换为设置和比较,具体取决于您是否需要重复
以避免重复,可以做
You can try split the column to list then sort and compare.
Or you can convert list to set and compare depending on if you want duplicated
To avoid repeating, you can do
许多方法可以做到这一点,一种方法是爆炸您的数组,对它们进行排序并匹配以保持平等。
Lots of ways to do this, one way would be to explode your arrays, sort them and match for equality.