You're looking to transform each row of your DataFrame using a function that returns a dictionary, and then convert those dictionaries into new columns in a resulting DataFrame.
Pandas' apply method, especially with axis=1 (to apply row-wise), combined with pd.Series or pd.DataFrame constructor, is the perfect tool for this.
Here's how you can do it, with examples:
Method 1: Using apply(axis=1).apply(pd.Series) (Most Concise)
This is often the most straightforward and idiomatic way.
- Apply your function to each row (
axis=1). This will result in a Series where each element is a dictionary.
- Then, apply
pd.Series to that resulting Series. Pandas is smart enough to convert each dictionary into a Series (where dictionary keys become Series indices), and then combine all these Series into a DataFrame, aligning by their (key) names.
import pandas as pd
# 1. Create a sample DataFrame
data = {
'product_id': [101, 102, 103, 104],
'price': [10.5, 20.0, 5.75, 12.25],
'quantity': [2, 1, 5, 3],
'category': ['Electronics', 'Books', 'Electronics', 'Books']
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
print("-" * 30)
# 2. Define the function that returns a dictionary
def process_product_row(row):
"""
Processes a product row and returns a dictionary with derived metrics.
"""
total_value = row['price'] * row['quantity']
is_expensive = total_value > 30.0
product_code = f"{row['category'][:3].upper()}-{row['product_id']}"
return {
'total_value': total_value,
'is_expensive': is_expensive,
'product_code': product_code,
'category_upper': row['category'].upper() # Example of simple transformation
}
# 3. Apply the function and convert the result into a DataFrame
# Step 1: Apply the function row-wise (axis=1)
# This results in a Series where each element is a dictionary
intermediate_series_of_dicts = df.apply(process_product_row, axis=1)
print("\nIntermediate Series (each element is a dict):")
print(intermediate_series_of_dicts)
print("-" * 30)
# Step 2: Convert the Series of dictionaries into a DataFrame
# Each dictionary's keys become column names
result_df = intermediate_series_of_dicts.apply(pd.Series)
print("\nResulting DataFrame:")
print(result_df)
print("-" * 30)
# You can also chain them directly:
chained_result_df = df.apply(process_product_row, axis=1).apply(pd.Series)
print("\nChained Result DataFrame (same as above):")
print(chained_result_df)
# You can also concatenate this new DataFrame with the original if needed
# df_combined = pd.concat([df, result_df], axis=1)
# print("\nCombined DataFrame:")
# print(df_combined)
Method 2: Using apply(axis=1).tolist() then pd.DataFrame()
This method collects all the dictionaries into a list first and then creates a DataFrame from that list. This can sometimes be slightly more memory-efficient or performant for very large datasets, as pd.DataFrame is highly optimized for taking a list of dictionaries.
import pandas as pd
# (Using the same df and process_product_row function from above)
# 1. Apply the function row-wise to get a Series of dictionaries
series_of_dicts = df.apply(process_product_row, axis=1)
# 2. Convert the Series of dictionaries into a list of dictionaries
list_of_dicts = series_of_dicts.tolist()
print("\nList of Dictionaries:")
print(list_of_dicts)
print("-" * 30)
# 3. Create a new DataFrame from the list of dictionaries
new_df_from_list = pd.DataFrame(list_of_dicts)
print("\nResulting DataFrame (from list of dicts):")
print(new_df_from_list)
Key Considerations:
- Function Signature: The function you pass to
df.apply(..., axis=1) will receive each row as a Pandas Series object. You can access values using row['column_name'].
- Column Names: The keys of the dictionaries returned by your function will automatically become the column names in the new DataFrame.
- Missing Keys: If some dictionaries returned by your function don't have all the same keys, Pandas will automatically fill the missing values with
NaN in the resulting DataFrame. This is generally desired behavior.
def partial_dict_func(row):
if row['product_id'] % 2 == 0:
return {'even_id_col': 'Yes', 'value_sq': row['price']**2}
else:
return {'odd_id_col': 'No'} # Missing 'even_id_col' and 'value_sq'
partial_df = df.apply(partial_dict_func, axis=1).apply(pd.Series)
print("\nDataFrame with missing keys (filled with NaN):")
print(partial_df)
- Performance:
- For extremely large DataFrames,
apply(axis=1) can be slow as it effectively loops through rows in Python.
- If your transformation can be expressed using vectorized Pandas operations (e.g., arithmetic, string methods directly on Series/Columns), that will always be faster.
- However, when your logic is complex and requires accessing multiple columns of a row and returning multiple derived values,
apply(axis=1) is often the most readable and direct approach.
- If
apply(axis=1) becomes a bottleneck, consider itertuples() for slightly better performance when iterating, though it's more verbose to construct the dictionaries manually.
Choose the method that you find most readable and fits your specific performance needs. For most use cases, df.apply(your_func, axis=1).apply(pd.Series) is excellent.