I have been attempting to replace strings in a data set for specific columns. Either with 1 or 0, 'Y' if 1, otherwise 0.
I have managed to identify which columns to target, using a dataframe to rdd conversion with a lambda, but it is taking a while to process.
A switch to an rdd is done for each column and then a distinct is performed, this is taking a while!
If a 'Y' exists in the distinct result set then the column is identified as requiring a transformation.
I was wondering if anyone can suggest how I can use pyspark sql functions exclusively to obtain the same result instead of having to switch for each column?
The code, on sample data, is as follows:
import pyspark.sql.types as typ
import pyspark.sql.functions as func
col_names = [
('ALIVE', typ.StringType()),
('AGE', typ.IntegerType()),
('CAGE', typ.IntegerType()),
('CNT1', typ.IntegerType()),
('CNT2', typ.IntegerType()),
('CNT3', typ.IntegerType()),
('HE', typ.IntegerType()),
('WE', typ.IntegerType()),
('WG', typ.IntegerType()),
('DBP', typ.StringType()),
('DBG', typ.StringType()),
('HT1', typ.StringType()),
('HT2', typ.StringType()),
('PREV', typ.StringType())
]
schema = typ.StructType([typ.StructField(c[0], c[1], False) for c in col_names])
df = spark.createDataFrame([('Y',22,56,4,3,65,180,198,18,'N','Y','N','N','N'),
('N',38,79,3,4,63,155,167,12,'N','N','N','Y','N'),
('Y',39,81,6,6,60,128,152,24,'N','N','N','N','Y')]
,schema=schema)
cols = [(col.name, col.dataType) for col in df.schema]
transform_cols = []
for s in cols:
if s[1] == typ.StringType():
distinct_result = df.select(s[0]).distinct().rdd.map(lambda row: row[0]).collect()
if 'Y' in distinct_result:
transform_cols.append(s[0])
print(transform_cols)
The output is :
['ALIVE', 'DBG', 'HT2', 'PREV']
I managed to use udf
in order to do the task. First, pick the column with Y
or N
(here I use func.first
in order to skim through the first row):
cols_sel = df.select([func.first(col).alias(col) for col in df.columns]).collect()[0].asDict()
cols = [col_name for (col_name, v) in cols_sel.items() if v in ['Y', 'N']]
# return ['HT2', 'ALIVE', 'DBP', 'HT1', 'PREV', 'DBG']
Next, You can create udf
function in order to map Y
, N
to 1
, 0
.
def map_input(val):
map_dict = dict(zip(['Y', 'N'], [1, 0]))
return map_dict.get(val)
udf_map_input = func.udf(map_input, returnType=typ.IntegerType())
for col in cols:
df = df.withColumn(col, udf_map_input(col))
df.show()
Finally, you can sum the column. I then transform output into dictionary and check which columns has value greater than 0 (ie contains Y
)
out = df.select([func.sum(col).alias(col) for col in cols]).collect()
out = out[0]
print([col_name for (col_name, val) in out.asDict().items() if val > 0])
Output
['DBG', 'HT2', 'ALIVE', 'PREV']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.