Как найти в столбце Dataframe отображение «один к одному» или «один ко многим» в pyspark? - PullRequest
0 голосов
/ 04 ноября 2018

У меня есть кадр данных, как показано ниже:

df0 = sc.parallelize([
    (1, 3),
    (2, 3),
    (1, 2)
   ]).toDF(["id",'t'])

когда я выполняю шоу:

df0.show()
+---+---+
| id|  t|
+---+---+
|  1|  3|
|  2|  3|
|  1|  2|
+---+---+

Я хочу определить связь между столбцами ID, т. В заданном df0 отношении между id столбцом и t есть отношение один ко многим, потому что столбец идентификатора 1 и столбец 3 столбца т. е. (1,3) и следующий (1,2). так один ко многим

мой ожидаемый результат будет как ниже:

+---+---+---+
|idt| id|  t|
+---+---+---+
| id| OO| OM|
|  t| OM| OO|
+---+---+---+

1 Ответ

0 голосов
/ 04 ноября 2018

Вы можете сделать это путем группировки и подсчета.

from pyspark.sql import functions as F
from pyspark.sql.functions import when
from pyspark.sql.types import *

def relation_type(df, fromCol, toCol):
    df2 = df.groupBy(fromCol)\
    .agg(F.countDistinct(toCol).alias('val_count'))\
    .agg(F.max('val_count').alias('max_rel_count'))

    return df2.withColumn('mapping', when(df2['max_rel_count'] > 1, 'OM')\
                   .otherwise('OO'))\
                    .drop('max_rel_count')

def relation_types(df, cols):
    schemaArr = [StructField('ColName', StringType(), True)]
    for i in cols:
        schemaArr.append(StructField(i, StringType(), True))
    schema = StructType(schemaArr)
    result = sqlContext.createDataFrame(sc.emptyRDD(), schema)
    for i in cols:
        rowDict = []
        rowDict.append(i)
        for j in cols:
            val = relation_type(df, i, j).collect()[0]
            rowDict.append(val['mapping'])
        row = sqlContext.createDataFrame([rowDict])
        result = result.union(row)
    return result

затем назовите его с нужными столбцами

relation_types(df, ['id', 't']).show()

результат

+-------+---+---+
|ColName| id|  t|
+-------+---+---+
|     id| OO| OM|
|      t| OM| OO|
+-------+---+---+
...