简体   繁体   English

如何在DataFrame中获取唯一的一对值

[英]How to get unique pairs of values in DataFrame

Given a pySpark DataFrame, how can I get all possible unique combinations of columns col1 and col2 . 给定pySpark DataFrame,我如何获得列col1col2所有可能的唯一组合。

I can get unique values for a single column, but cannot get unique pairs of col1 and col2 : 我可以为单个列获取唯一值,但是不能获得col1col2唯一对:

df.select('col1').distinct().rdd.map(lambda r: r[0]).collect()

I tried this, but it doesn't seem to work: 我试过了,但是似乎不起作用:

df.select(['col1','col2']).distinct().rdd.map(lambda r: r[0]).collect()

The one I tried, 我尝试过的那个

>>> df = spark.createDataFrame([(1,2),(1,3),(1,2),(2,3)],['col1','col2'])
>>> df.show()
+----+----+
|col1|col2|
+----+----+
|   1|   2|
|   1|   3|
|   1|   2|
|   2|   3|
+----+----+

>>> df.select('col1','col2').distinct().rdd.map(lambda r:r[0]).collect() ## your mapping
[1, 2, 1]
>>> df.select('col1','col2').distinct().show()
+----+----+
|col1|col2|
+----+----+
|   1|   3|
|   2|   3|
|   1|   2|
+----+----+
>>> df.select('col1','col2').distinct().rdd.map(lambda r:(r[0],r[1])).collect() 
[(1, 3), (2, 3), (1, 2)]

请尝试以下功能:

    `df[['col1', 'col2']].drop_duplicates()`

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM