Add columns to dataframe from a dictionary

There are many answers out there to this question, but I couldn’t find one that applies to my case.

I have a dataframe that contains ID’s:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df = pd.DataFrame({"id": [0, 1, 2, 3, 4]})
</code>
<code>df = pd.DataFrame({"id": [0, 1, 2, 3, 4]}) </code>
df = pd.DataFrame({"id": [0, 1, 2, 3, 4]})

Now, I query a REST API for each ID’s to get additional attributes that are returned to me as a dictionary:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{"id": 0, "values": {"first_name": "Bob", "last_name": "Smith"}}
</code>
<code>{"id": 0, "values": {"first_name": "Bob", "last_name": "Smith"}} </code>
{"id": 0, "values": {"first_name": "Bob", "last_name": "Smith"}}

What I want is to add the content of values as additional columns to the matching row of the dataframe.

An important point is that, at each iteration, I may get different attributes, so I don’t know how many columns will be added in the end, or even their names. So, sometimes I need to add a column (which I would do with pd.concat), but sometimes I need to set the value to an existing one.

id first_name last_name something something_else
0 Bob Smith
4

Any thought?

Code

your example

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import pandas as pd
df = pd.DataFrame({"id": [0, 1, 2, 3, 4]})
data = {"id": 0, "values": {"first_name": "Bob", "last_name": "Smith"}}
</code>
<code>import pandas as pd df = pd.DataFrame({"id": [0, 1, 2, 3, 4]}) data = {"id": 0, "values": {"first_name": "Bob", "last_name": "Smith"}} </code>
import pandas as pd

df = pd.DataFrame({"id": [0, 1, 2, 3, 4]})
data = {"id": 0, "values": {"first_name": "Bob", "last_name": "Smith"}}

code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># make data dict to dataframe (For multiple dict, use concat)
d = pd.json_normalize(data)
# merge
out = df.merge(d, how='left')
</code>
<code># make data dict to dataframe (For multiple dict, use concat) d = pd.json_normalize(data) # merge out = df.merge(d, how='left') </code>
# make data dict to dataframe (For multiple dict, use concat)
d = pd.json_normalize(data)

# merge
out = df.merge(d, how='left')

out:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> id values.first_name values.last_name
0 0 Bob Smith
1 1 NaN NaN
2 2 NaN NaN
3 3 NaN NaN
4 4 NaN NaN
</code>
<code> id values.first_name values.last_name 0 0 Bob Smith 1 1 NaN NaN 2 2 NaN NaN 3 3 NaN NaN 4 4 NaN NaN </code>
   id values.first_name values.last_name
0   0               Bob            Smith
1   1               NaN              NaN
2   2               NaN              NaN
3   3               NaN              NaN
4   4               NaN              NaN

If you want to remove value. from a column name, you can use the rename function or the str.replace function.

I agree there are many ways out there to do this. You can do it this way with List Comprehension approach which will be Faster I guess, and will handle dynamic columns well.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import pandas as pd
df = pd.DataFrame({"id": [0, 1, 2, 3, 4]})
# Simulated API response
def get_api_data(id):
data = {
0: {"first_name": "Bob", "last_name": "Smith"},
1: {"first_name": "Alice", "something": "extra"},
2: {"last_name": "Jones", "something_else": "value"},
3: {"first_name": "Charlie", "age": 30},
4: {} # No data available for this ID
}
return data.get(id, {})
def update_dataframe(df):
all_columns = set()
data_list = []
for _, row in df.iterrows():
api_data = get_api_data(row['id'])
all_columns.update(api_data.keys())
row_data = row.to_dict()
row_data.update(api_data)
data_list.append(row_data)
result_df = pd.DataFrame(data_list, columns=list(all_columns) + list(df.columns))
return result_df
updated_df = update_dataframe(df)
print(updated_df)
</code>
<code>import pandas as pd df = pd.DataFrame({"id": [0, 1, 2, 3, 4]}) # Simulated API response def get_api_data(id): data = { 0: {"first_name": "Bob", "last_name": "Smith"}, 1: {"first_name": "Alice", "something": "extra"}, 2: {"last_name": "Jones", "something_else": "value"}, 3: {"first_name": "Charlie", "age": 30}, 4: {} # No data available for this ID } return data.get(id, {}) def update_dataframe(df): all_columns = set() data_list = [] for _, row in df.iterrows(): api_data = get_api_data(row['id']) all_columns.update(api_data.keys()) row_data = row.to_dict() row_data.update(api_data) data_list.append(row_data) result_df = pd.DataFrame(data_list, columns=list(all_columns) + list(df.columns)) return result_df updated_df = update_dataframe(df) print(updated_df) </code>
import pandas as pd

df = pd.DataFrame({"id": [0, 1, 2, 3, 4]})

# Simulated API response
def get_api_data(id):
    data = {
        0: {"first_name": "Bob", "last_name": "Smith"},
        1: {"first_name": "Alice", "something": "extra"},
        2: {"last_name": "Jones", "something_else": "value"},
        3: {"first_name": "Charlie", "age": 30},
        4: {}  # No data available for this ID
    }
    return data.get(id, {})

def update_dataframe(df):
    all_columns = set()
    data_list = []
    
    for _, row in df.iterrows():
        api_data = get_api_data(row['id'])
        all_columns.update(api_data.keys())
        row_data = row.to_dict()
        row_data.update(api_data)
        data_list.append(row_data)
    
    result_df = pd.DataFrame(data_list, columns=list(all_columns) + list(df.columns))
    
    return result_df

updated_df = update_dataframe(df)
print(updated_df)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> id first_name last_name something something_else age
0 0 Bob Smith NaN NaN NaN
1 1 Alice NaN extra NaN NaN
2 2 NaN Jones NaN value NaN
3 3 Charlie NaN NaN NaN 30.0
4 4 NaN NaN NaN NaN NaN
</code>
<code> id first_name last_name something something_else age 0 0 Bob Smith NaN NaN NaN 1 1 Alice NaN extra NaN NaN 2 2 NaN Jones NaN value NaN 3 3 Charlie NaN NaN NaN 30.0 4 4 NaN NaN NaN NaN NaN </code>
   id first_name last_name something something_else   age
0   0        Bob     Smith       NaN            NaN   NaN
1   1      Alice       NaN     extra            NaN   NaN
2   2        NaN     Jones       NaN          value   NaN
3   3    Charlie       NaN       NaN            NaN  30.0
4   4        NaN       NaN       NaN            NaN   NaN

Another possible solution, whose steps are:

  • First, it converts the dictionary d into a dataframe using pd.DataFrame.

  • Then, it resets the index of this dataframe with reset_index.

  • Next, it pivots the dataframe using pivot to reshape it, setting id as the index, values as the values, and index as the columns.

  • After pivoting, it resets the index again and removes the axis name with rename_axis.

  • Finally, it merges this transformed dataframe with the original dataframe df on the id column using merge.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>df.merge(
pd.DataFrame(d).reset_index()
.pivot(index='id', values='values', columns='index')
.reset_index().rename_axis(None, axis=1), on='id', how='left')
</code>
<code>df.merge( pd.DataFrame(d).reset_index() .pivot(index='id', values='values', columns='index') .reset_index().rename_axis(None, axis=1), on='id', how='left') </code>
df.merge(
    pd.DataFrame(d).reset_index()
    .pivot(index='id', values='values', columns='index')
    .reset_index().rename_axis(None, axis=1), on='id', how='left')

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> id first_name last_name
0 0 Bob Smith
1 1 NaN NaN
2 2 NaN NaN
3 3 NaN NaN
4 4 NaN NaN
</code>
<code> id first_name last_name 0 0 Bob Smith 1 1 NaN NaN 2 2 NaN NaN 3 3 NaN NaN 4 4 NaN NaN </code>
   id first_name last_name
0   0        Bob     Smith
1   1        NaN       NaN
2   2        NaN       NaN
3   3        NaN       NaN
4   4        NaN       NaN

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật