Swap String part in all dataframe columns

Asked

Viewed 1,933 times

5

I have a dataframe in the following template:

lista = []
lista.append(['A1','2','A3'])
lista.append(['4','A5','6'])
lista.append(['A7','8','9'])

df = pd.DataFrame(lista, columns=['A', 'B', 'C'])

df:
inserir a descrição da imagem aqui

What I want is to remove the character 'To' of all columns. I know I can get it out by going column by column with the command (df. Series):

df.A.replace('A', '', regex = True)
df.B.replace('A', '', regex = True)
df.C.replace('A', '', regex = True)

Upshot:

inserir a descrição da imagem aqui

However, I would like to set up a function that goes through my dataframe removing this specific character.

I tried to perform an iteration on the columns and pick each one up as follows:

for column in df.columns[1:]:
    print(column)
    df[column] = df.column.replace('A', '', regex = True)

But the following error returns to me:

Attributeerror: 'Dataframe' Object has no attribute 'column'

Any idea?

1 answer

4


You can use the predefined function replace, as follows:

df.replace({'A': ''}, regex=True, inplace=True) 

Given your dataframe, the result will be:

   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9
  • 1

    I wasn’t aware of the possibility of not using the command replace directly. It worked very well, thank you very much!

Browser other questions tagged

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