I recently applied a transformation to unnest a nested json, in order to have a flat dataset to work with, and while the transformation works, the final format is not the one I am looking for. It compressed all the data into a single row and added suffixes to column names, instead of separating into different columns for each id_prop.
My dataset in JSON format to replicate with Pandas:
import pandas as pd
json = {"id_prop.0":{"0":1},"id_prop.1":{"0":2},"id_prop.2":{"0":3},"prop_number.0":{"0":123},"prop_number.1":{"0":325},"prop_number.2":{"0":754},"prop_value.0":{"0":1},"prop_value.1":{"0":1},"prop_value.2":{"0":1}}
df = pd.DataFrame.from_dict(json, orient='columns')
My result:
| id_prop.0 | id_prop.1 | id_prop.2 | prop_number.0 | prop_number.1 | prop_number.2 | prop_value.0 | prop_value.1 | prop_value.2 | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 123 | 325 | 754 | 1 | 1 | 1 |
The result I expect:
| id_prop | prop_number | prop_value | |
|---|---|---|---|
| 0 | 1 | 123 | 1 |
| 1 | 2 | 325 | 1 |
| 2 | 3 | 754 | 1 |
Is there any way to pivot the dataframe into the format I need, where each row represents the values of a single id_prop?
Attemps
I have already extracted the names of the columns I need without suffixes:
def extract_cols(columns):
myset = set()
myset_add = myset.add
return [x for x in columns if not (x in myset or myset_add(x))]
cols = extract_cols(df.columns.str.replace("\.[0-9]", "", regex=True))
And also "verticalized" the results I need using stack():
df_stacked = df.stack().reset_index(level=1, drop=True)
But I haven't figured out how to combine that info yet. Any help would be highly appreciated.
Extra:
If there is also a way to apply this using pyspark, then much better!