I have a Spark dataframe like this...
| ID | A | B | C | D |
|---|---|---|---|---|
| id1 | 1 | 0 | 0 | 2 |
| id2 | 0 | 3 | 0 | 1 |
| id3 | 1 | 2 | 5 | 0 |
| id4 | 4 | 0 | 0 | 1 |
I would like to have a new dataframe which is based on this logic...
- Accept any column which has positive values
- Concatenate their names
The result would then be like this...
| ID | NewColumn |
|---|---|
| id1 | A,D |
| id2 | B,D |
| id3 | A,B,C |
| id4 | A,D |
My Effort:
A) For the first step I thought I will convert the integers into the name of the columns... So it will look like this...
| ID | A | B | C | D |
|---|---|---|---|---|
| id1 | A | 0 | 0 | D |
| id2 | 0 | B | 0 | D |
| id3 | A | B | C | 0 |
| id4 | A | 0 | 0 | D |
I was trying with a UDF but it did not work...
def CountSelect(colname, x):
if x>0 :
return colname
else:
return ""
countUDF = UserDefinedFunction(CountSelect, T.StringType())
cols = inoutDF.columns
cols.remove("ID")
intermediateDF = inputDF.select("ID", *(countDF(c, col(c)).alias(c) for c in cols))
BUT it is not working...
Can any of you help please?
B) Then I will use string concat function on all the columns
This part should be easier but still if you can combine both logic into a simpler working code, I would be really thankful to you.
Thanks a lot