Reputation: 196
I have a dataframe as follows:
venue innings batting_team bowling_team score batsmen
M Chinnaswamy Stadium 1 Kolkata Knight Riders Royal Challengers Bangalore 61 [SC Ganguly, BB McCullum, RT Ponting]
M Chinnaswamy Stadium 2 Royal Challengers Bangalore Kolkata Knight Riders 26 [R Dravid, W Jaffer, V Kohli, JH Kallis, CL White, MV Boucher]
Feroz Shah Kotla 1 Rajasthan Royals Delhi Daredevils 40 [T Kohli, YK Pathan, SR Watson, M Kaif]
Feroz Shah Kotla 2 Delhi Daredevils Rajasthan Royals 55 [G Gambhir, V Sehwag, S Dhawan]
Wankhede Stadium 1 Mumbai Indians Royal Challengers Bangalore 47 [L Ronchi, ST Jayasuriya, DJ Thornely, RV Uthappa, PR Shah]
Wankhede Stadium 2 Royal Challengers Bangalore Mumbai Indians 40 [S Chanderpaul, R Dravid, LRPL Taylor]
Eden Gardens 1 Deccan Chargers Kolkata Knight Riders 39 [AC Gilchrist, Y Venugopal Rao, VVS Laxman, A Symonds]
Eden Gardens 2 Kolkata Knight Riders Deccan Chargers 26 [WP Saha, BB McCullum, RT Ponting, SC Ganguly, DJ Hussey]
Sawai Mansingh Stadium 1 Kings XI Punjab Rajasthan Royals 54 [K Goel, JR Hopes, KC Sangakkara]
Sawai Mansingh Stadium 2 Rajasthan Royals Kings XI Punjab 53 [M Kaif, YK Pathan, Kamran Akmal, SR Watson, DS Lehmann]
As it can be seen, the batsmen
column has lists as its elements. Now I need to sort each list. I used the code
df['batsmen'] = df['batsmen'].sort()
but I get the error as Series object as no attribute 'sort'
. How can I achieve this so that each list in the column gets sorted in ascending order?
Upvotes: 0
Views: 75
Reputation: 195438
Another solution, if you want to do it in-place:
df["batsmen"].apply(list.sort)
print(df)
EDIT: For numpy.ndarray
:
df["batsmen"].apply(np.ndarray.sort)
print(df)
Upvotes: 1
Reputation: 11
Try df.sort_values(by="batsmen").head()
https://pandas.pydata.org/docs/getting_started/intro_tutorials/07_reshape_table_layout.html
Upvotes: 1
Reputation: 30022
Try
df['batsmen'] = df['batsmen'].apply(sorted)
If you want to reverse the list, you can do
df['batsmen'] = df['batsmen'].apply(lambda x: sorted(x, reversed=True))
Upvotes: 2