The pandas implementation combines the larger values in two columns into a new column

  • 2021-10-15 11:03:50
  • OfStack

The last development requirement requires pandas to implement this requirement:

Compare the two columns row by row, and select the larger value in each row and two columns to add to the third column

It seems that there is no similar function, so there is no way to build wheels by yourself, and directly on the code and comments


#  The values to be compared are value_x And value_y
#  The column name of the new home is value_final
# 1. Settings 1 A flag, Value is value_y-value_x, Is a positive representation y Larger, negative representative x Larger 
df_test['value_flag'] = df_test['Value_y'] - df_test['Value_x']
# 2. Acquire separately y The larger part and x The larger part 
df_test_bigger = df_test[df_test['value_flag'] >= 0].copy()
df_test_litter = df_test[df_test['value_flag'] < 0].copy()
# 3. Pair separately final Perform an assignment 
df_test_bigger['Value_Final'] = df_test_bigger['Value_y']
df_test_litter['Value_Final'] = df_test_litter['Value_x']
# 4. Use concat Function to aggregate it 
df_test_1 = pd.concat([df_test_bigger, df_test_litter])

Supplement: pandas Tip-Two columns add up to form a new 1 column (eval)

As follows:


data.eval(' New Field = Field 1+ Field 2',inplace=True)
data.eval(""" New Field 1= Field 1+ Field 2
   New Field 2= Field 1+ Field 2
   New Field 3= Field 1+ Field 2""",inplace=True)

Related articles: