Sort dataframe by string length

2024/11/20 22:00:33

I want to sort by name length. There doesn't appear to be a key parameter for sort_values so I'm not sure how to accomplish this. Here is a test df:

import pandas as pd
df = pd.DataFrame({'name': ['Steve', 'Al', 'Markus', 'Greg'], 'score': [2, 4, 2, 3]})
Answer

You can use reindex of index of Series created by len with sort_values:

print (df.name.str.len())
0    5
1    2
2    6
3    4
Name: name, dtype: int64print (df.name.str.len().sort_values())
1    2
3    4
0    5
2    6
Name: name, dtype: int64s = df.name.str.len().sort_values().index
print (s)
Int64Index([1, 3, 0, 2], dtype='int64')print (df.reindex(s))name  score
1      Al      4
3    Greg      3
0   Steve      2
2  Markus      2

df1 = df.reindex(s)
df1 = df1.reset_index(drop=True)
print (df1)name  score
0      Al      4
1    Greg      3
2   Steve      2
3  Markus      2
https://en.xdnf.cn/q/26254.html

Related Q&A

How to mock pythons datetime.now() in a class method for unit testing?

Im trying to write tests for a class that has methods like:import datetime import pytzclass MyClass:def get_now(self, timezone):return datetime.datetime.now(timezone)def do_many_things(self, tz_string=…

How can I select only one column using SQLAlchemy?

I want to select (and return) one field only from my database with a "where clause". The code is:from sqlalchemy.orm import load_only@application.route("/user", methods=[GET, POST])…

Get first list index containing sub-string?

For lists, the method list.index(x) returns the index in the list of the first item whose value is x. But if I want to look inside the list items, and not just at the whole items, how do I make the mos…

TypeError: Invalid dimensions for image data when plotting array with imshow()

For the following code# Numerical operation SN_map_final = (new_SN_map - mean_SN) / sigma_SN # Plot figure fig12 = plt.figure(12) fig_SN_final = plt.imshow(SN_map_final, interpolation=nearest) plt.col…

How to give delay between each requests in scrapy?

I dont want to crawl simultaneously and get blocked. I would like to send one request per second.

preprocess_input() method in keras

I am trying out sample keras code from the below keras documentation page, https://keras.io/applications/What preprocess_input(x) function of keras module does in the below code? Why do we have to do …

How to calculate precision and recall in Keras

I am building a multi-class classifier with Keras 2.02 (with Tensorflow backend),and I do not know how to calculate precision and recall in Keras. Please help me.

Django set range for integer model field as constraint

I have a django model,class MyModel(models.Model)qty = model.IntegerField()where I want to set constraint for qty something like this, >0 or <0,i.e the qty can be negative or positive but can no…

Increase resolution with word-cloud and remove empty border

I am using word cloud with some txt files. How do I change this example if I wanted to 1) increase resolution and 2) remove empty border. #!/usr/bin/env python2 """ Minimal Example =====…

How can I check if a list index exists?

Seems as thoughif not mylist[1]:return FalseDoesnt work.