简体   繁体   中英

PySPark: How to create JSON and CSV file from a variable in pyspark?

I am trying to write the results of a variable to a csv file and then create a json out of it. Each iteration of the for loop will write the below result to the variable res_df. If it is possible to directly create a json without creating a csv , than also i would be happy to implement the same. Please help.

'var_id', 10000001, 14003088.0, 14228946.912793402, 1874168.857698741, 15017976.0, 18000192, 0

Now i want to append this result into a csv file and then create a json out of it. I had achieved it in my python code. Now need your help on how to achieve the same in pyspark

Python Code:

res_df=line,x.min(),np.percentile(x, 25),np.mean(x),np.std(x),np.percentile(x, 75),x.max(),df[line].isnull().mean() * 100
        with open(data_output_file, 'a', newline='') as csvfile:
            writerows = csv.writer(csvfile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_MINIMAL)
            writerows.writerow(map(lambda x: x, res_df))

quality_json_df = pd.read_csv(r'./DQ_RESULT.csv')
# it will dump json to file
quality_json_df.to_json("./Dq_Data.json", orient="records")

My Pyspark Code

for line in tcp.collect():
        #print value in MyCol1 for each row                
        print line
        v3=np.array(data.select(line).collect())
        x = v3[np.logical_not(np.isnan(v3))] 
        print(x)
        cnt_null=data.filter((data[line] == "") | data[line].isNull() | isnan(data[line])).count()
        print(cnt_null)
        res_df=line,x.min(),np.percentile(x, 25),np.mean(x),np.std(x),np.percentile(x, 75),x.max(),cnt_null
        print(res_df)
json_output = []
column_statistic = ["variable_name", "min", "Q1", "mean", "std", "Q3", "max", "null_value"]
for line in tcp.collect():
        # print value in MyCol1 for each row
        print
        line
        v3 = np.array(data.select(line).collect())
        x = v3[np.logical_not(np.isnan(v3))]
        notnan_cnt = np.count_nonzero(v3)
        print(x)
        cnt_null = data.filter((data[line] == "") | data[line].isNull() | isnan(data[line])).count()
        print(cnt_null, notnan_cnt)
        res_df = [str(line), x.min(), np.percentile(x, 25), np.mean(x), np.std(x), np.percentile(x, 75), x.max(), cnt_null]
        json_row = {key: value for key, value in zip(column_statistic, res_df)}
        json_output.append(json_row)
        print(res_df) 

with open("json_result.json", "w") as fp:
                json.dump(json_output, fp)

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.

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