Python: Pandas: two columns with same values, alphabetically sorted and stored
pandas, python
Solution
As an alternative vectorized solution, you can use `numpy.minimum()` and `numpy.maximum()`:
import numpy as np
df['restart_A'] = np.minimum(df['name_A'], df['name_B'])
df['restart_B'] = np.maximum(df['name_A'], df['name_B'])
Or use `apply` method:
df[['restated_A', 'restated_B']] = df.apply(lambda r: sorted(r), axis = 1)
Problem
Problem "The df has two columns but sometimes filled with the same values. We need to re-save them into two new columns but in alphabetical order" Context We have a pandas df like this: ``` df = pd.DataFrame([{"name_A": "john", "name_B": "mac"}, {"name_A": "mac", "name_B": "john"}]) ``` Like this: ``` name_A | name_B john | mac mac | john Trump | Clinton ``` Desired Output ``` name_A | name_B | restated_A | restated_B john | mac | john | mac mac | john | john | mac trump | clinton | clinton | trump ``` In words, we wish to have the columns' values `name_A` and `name_B` to be alphabetically sorted in `restated_A` AND `restated_B` Tried so far bunch of lambdas but couldn't get it to work Specifications Python: 3.5.2 Pandas: 0.18.1