In Python, how do you remove specific characters from all the records of just one particular column?

Asked

Viewed 260 times

5

I’m at Jupyter Notebook working with Python.

The dataframe has some columns, but in a specific column I want to delete all records that end with ". txt", meaning the last 4 characters.

Image of the dataframe: Imagem do dataframe

I want to have all these lines without the characters ". txt".

2 answers

4


Another way, besides using map (as pointed out in another reply), is to use the conversion and string methods provided by pandas, thus:

raw_data['nome_arquivo'].str.rstrip('.txt')

The above snippet is only one of the solutions, but any other string method can be used after the .str, such as the replace (raw_data['nome_arquivo'].str.replace('.txt', '')).

  • Thanks, this command worked on the way out. However, when running the raw_data dataframe again, it displays all the other columns and this, but without the previous setting without the ". txt".

  • @Perciliano has to do raw_data['nome_arquivo'] = raw_data['nome_arquivo'].str.rstrip('.txt')

3

You can use apply and slicing the string

raw_data['nome_arquivo'] = raw_data['nome_arquivo'].apply(lambda x: x[:-4])

You can also use replace

raw_data['nome_arquivo'] = raw_data['nome_arquivo'].str.replace('.txt','')

Entree

                                        ARQUIVOS
0   AAAAAAAAAAAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB.txt
1   AAAAAAAAAAAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB.txt
2   AAAAAAAAAAFFFBBBBBBBBBBBBB.txt
3   AAAAAAAAAAAFFFFFFFFFFFBBBBBBB.txt
4   AAAAAAAAAAAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB.txt
5   AAAAAAAAAAAFFFFFFFFFFBBBBBBBBBBBBB.txt
6   AAAAAAAAAAAFFFFBBBBBBBBBBBBB.txt
7   AAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB.txt

Exit

                                    ARQUIVOS
0   AAAAAAAAAAAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB
1   AAAAAAAAAAAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB
2   AAAAAAAAAAFFFBBBBBBBBBBBBB
3   AAAAAAAAAAAFFFFFFFFFFFBBBBBBB
4   AAAAAAAAAAAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB
5   AAAAAAAAAAAFFFFFFFFFFBBBBBBBBBBBBB
6   AAAAAAAAAAAFFFFBBBBBBBBBBBBB
7   AAFFFFFFFFFFFFFFFFBBBBBBBBBBBBB
  • Thank you, but these commands did not work.

  • @Perciliano, I updated the answer, see if it works now. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.