Reputation: 111
I have a Json array with key value pairs like below
[
[
{
"value":"Dimension1",
"formattedValue":"Dimension1"
},
{
"value":"In",
"formattedValue":"In"
},
{
"value":"Amount1",
"formattedValue":"Amount1"
},
{
"value":"100",
"formattedValue":"100"
}
],
[
{
"value":"Dimension1",
"formattedValue":"Dimension1"
},
{
"value":"In",
"formattedValue":"In"
},
{
"value":"Amount2",
"formattedValue":"Amount2"
},
{
"value":"200",
"formattedValue":"200"
}
],
[
{
"value":"Dimension1",
"formattedValue":"Dimension1"
},
{
"value":"Out",
"formattedValue":"Out"
},
{
"value":"Amount1",
"formattedValue":"Amount1"
},
{
"value":"30",
"formattedValue":"30"
}
],
[
{
"value":"Dimension1",
"formattedValue":"Dimension1"
},
{
"value":"Out",
"formattedValue":"Out"
},
{
"value":"Amount2",
"formattedValue":"Amount2"
},
{
"value":"4",
"formattedValue":"40"
}
]
]
I have flatted this in to a table like below using python
data='<jsonstring>'
data= json.loads(data)
df = pd.DataFrame(data).stack().map(lambda x:x.get('formattedValue')).unstack()
df.columns = ['column0','column1','column2','column3']
df.rename({'column0' : 'Dimension','column1' : 'Type'}, axis=1,inplace=True)
df=df.pivot_table(index=['Dimension','Type'],columns=['column2'],values="column3",aggfunc='sum').reset_index()
Dimension | Type | Amount1 | Amount2 |
---|---|---|---|
Dimension1 | In | 100 | 200 |
Dimension1 | Out | 30 | 40 |
I want the first column value grouped so it only displays one time at the first row. like below. How do I achieve this please?
Dimension | Type | Amount1 | Amount2 |
---|---|---|---|
Dimension1 | In | 100 | 200 |
Out | 30 | 40 |
Upvotes: 0
Views: 48
Reputation: 11395
You can either use @AnuragDabas’ solution from the comments, combined with .rename_axis()
to remove the index names:
>>> df.set_index(['Dimension', 'Type']).rename_axis([None, None])
Amount1 Amount2
Dimension1 In 100 200
Out 30 40
Or you can use .mask()
to remove the duplicated rows:
>>> df['Dimension'] = df['Dimension'].mask(df['Dimension'].duplicated(), '')
>>> df
Dimension Type Amount1 Amount2
0 Dimension1 In 100 200
1 Out 30 40
Upvotes: 2