python - Saving a pandas dataframe to separate jsons without NaNs -
i have dataframe nan values.
here sample dataframe:
sample_df = pd.dataframe([[1,np.nan,1],[2,2,np.nan], [np.nan, 3, 3], [4,4,4],[np.nan,np.nan,5], [6,np.nan,np.nan]])
it looks like:
what did after json:
sample_df.to_json(orient = 'records')
which gives:
'[{"0":1.0,"1":null,"2":1.0},{"0":2.0,"1":2.0,"2":null},{"0":null,"1":3.0,"2":3.0},{"0":4.0,"1":4.0,"2":4.0},{"0":null,"1":null,"2":5.0},{"0":6.0,"1":null,"2":null}]'
i want save dataframe json 2 rows in each json, none of nan values. here how tried it:
df_dict = dict((n, sample_df.iloc[n:n+2, :]) n in range(0, len(sample_df), 2)) k, v in df_dict.items(): print(k) print(v) d in (v.to_dict('record')): k,v in list(d.items()): if type(v)==float: if math.isnan(v): del d[k] json.dumps(df_dict)
output want:
'[{"0":1.0,"2":1.0},{"0":2.0,"1":2.0}]' -> in 1 .json file '[{"1":3.0,"2":3.0},{"0":4.0,"1":4.0,"2":4.0}]' -> in second .json file '[{"2":5.0},{"0":6.0}]' -> in third .json file
use apply
drop nan
s, groupby
group , dfgroupby.apply
jsonify.
s = sample_df.apply(lambda x: x.dropna().to_dict(), 1)\ .groupby(sample_df.index // 2)\ .apply(lambda x: x.to_json(orient='records')) s 0 [{"0":1.0,"2":1.0},{"0":2.0,"1":2.0}] 1 [{"1":3.0,"2":3.0},{"0":4.0,"1":4.0,"2":4.0}] 2 [{"2":5.0},{"0":6.0}] dtype: object
finally, iterate on .values
, save separate json files.
import json i, j_data in enumerate(s.values): json.dump(j_data, open('file{}.json'.format(i + 1), 'w'))
Comments
Post a Comment