I want to use the apply
function to sort each row of a dataframe df
:
ID Student1 Student2 Student3
1 A B C
2 M E F
3 H A D
The code is
import numpy as np
import pandas as pd
df = pd.DataFrame(data=np.array([[1, 'A', 'B', 'C'], [2, 'M', 'E', 'F'], [3, 'H', 'A', 'D']]), columns=['ID', 'Student1', 'Student2', 'Student3'])
df1 = df.apply(np.sort, axis = 1)
df1
is a dataframe, not a series object. It looks like this:
ID Student1 Student2 Student3
1 A B C
2 E F M
3 A D H
How can I get a dataframe of the following? Thanks.
ID
1 [A, B, C]
2 [E, F, M]
3 [A, D, H]