'how to add columns and values in a dataframe in python
In the below JSON array
{
"data": [
{
"name": "page_call_phone_clicks_logged_in_unique",
"period": "lifetime",
"values": [
{
"value": 0
}
],
"title": null,
"description": "Number of people who logged in to Facebook and clicked the Call Now button.",
"id": "2342/insights/page_call_phone_clicks_logged_in_unique/lifetime"
},
{
"name": "page_actions_post_reactions_total",
"period": "lifetime",
"values": [
{
"value": {}
}
],
"title": null,
"description": "Daily total post reactions of a page by type.",
"id": "2324/insights/page_actions_post_reactions_total/lifetime"
},
{
"name": "page_consumptions_by_consumption_type",
"period": "day",
"values": [
{
"value": {},
"end_time": "2020-11-02T08:00:00+0000"
}
],
"title": "Daily Page Consumptions By Type",
"description": "Daily: The number of clicks on any of your content, by type. Stories generated without clicks on page content (e.g., liking the page in Timeline) are not included. (Total Count)",
"id": "432234/insights/page_consumptions_by_consumption_type/day"
}
]
}
I want the value of name as column name and the value of values as a column value
, for example :
Expected Output
that is a single row, but I'm getting the frame as shown in the picture below
Actual Output
I have tried the below code:
for data_obj in data['data']:
column_name = data_obj['name']
column_value = data_obj['values']
df_results= df_results.append({column_name:column_value}, ignore_index=True)
but it's not working properly, can anyone help me out on this
Solution 1:[1]
.append appends a dataframe by a row. This is why you are getting a new row for every iteration.To set columns you can simply use df[column_name] = value
. So for your use case it should look something like this.
df_results = pd.DataFrame()
for data_obj in data['data']:
column_name = data_obj['name']
column_value = data_obj['values']
df_results[column_name] = column_value
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Burschken |