Home > Software design >  How to sort a dataframe with a special character?
How to sort a dataframe with a special character?

Time:06-13

I want to sort a column dataframe with a special character '@'(see link). With everything that begins with '@'.

Here is a photo of the dataframe.

Dataframe with the column 'text'

If anyone has an idea how to do it? I would be thankful

CodePudding user response:

If you just want to filter the dataframe by a string column, you can use the str attribute:

import pandas as pd
df = pd.DataFrame(data=["@a", "@c", "@b", "a","d"], columns=["Text"])
df[df.Text.str.startswith("@")]

[output]:
   Text
0   @a
1   @c
2   @b

CodePudding user response:

I'm certain there is a better way, but a work around could be:

df['sortme'] = 1
df.loc[df['Text'].str.startswith('@'), 'sortme'] = 0
df.sort_values(['sortme', 'Text'])
  • Related