Search⌘ K
AI Features

Solution: Summing and Swapping

Explore how to calculate the sum of minimum and maximum values across rows and columns in a Pandas DataFrame. Learn how to use NumPy functions to extract these values, add new columns to store the sums, and swap values correctly using deep copies to avoid reference issues. This lesson strengthens your data manipulation skills for predictive data analysis.

We'll cover the following...

Solution #

Python 3.5
def Sum_Swap(df):
minm_r = np.min(df, axis = 1) # Get minimum elements from all rows
maxm_r = np.max(df, axis = 1) # Get maximum elements from all rows
df['row_sum'] = minm_r + maxm_r # Add the min & max values and assign them to new column
minm_c = np.min(df, axis = 0) # Get minimum elements from all columns
maxm_c = np.max(df, axis = 0) # Get maximum elements from all columns
df.loc['col_sum'] = minm_c + maxm_c # Add the min & max values and assign them to new row
a, b = df['row_sum'].copy(), df.loc['col_sum'].copy() # Store values of row and column in temparory variables
df['row_sum'], df.loc['col_sum'] = b, a # Interchange the values
return df
# Test Code
df = pd.DataFrame(np.random.randint(1, 100, 25).reshape(5, 5))
df_res = Sum_Swap(df.copy())
print(df_res)

Explanation

A function Sum_Swap is declared with df passed to it as a parameter.

  • On line 3, the np.min function is applied on the DataFrame to retrieve all the minimum values from each row. The axis=1 indicates that operation should only be performed on the rows. A Series is returned containing the minimum values for each ...