How to Combine or Merge Pandas Dataframe Columns

Python
Data Preprocessing

Here we have two ways to combine existing columns as a new one. Note all the methods below can be extended to include more than two columns.

 1|  # 1. Take the sum of the columns
 2|  df['col_3'] = df['col_1'] + df['col_2']
 3|  
 4|  # 2. Take the max of the columns
 5|  df['col_3'] = df.apply(lambda x: max(x.col_1, x.col_2),axis=1)
 6|  
 7|  # 3. Take the min of the columns
 8|  df['col_3'] = df.apply(lambda x: min(x.col_1, x.col_2),axis=1)
 9|  
10|  # 4. Take the average of the columns
11|  df['col_3'] = df.apply(lambda x: (x.col_1 + x.col_2) / 2, axis=1)
1 Upvote
Tags: Pandas | Combine
Did you find this snippet useful?

Sign up to bookmark this in your snippet library

Normalize Windowed Time Series
Python
Data Preprocessing

Scaler | Normalize | Scale | Min-max

4
Pivoting Pandas Dataframes
Python
Data Preprocessing

Pandas

3