viejoEngineer
viejoEngineer

Reputation: 404

Pandas chaining only modifying one column in dataframe using apply or pipe

I'm trying to clean a file using pandas chaining and I have come to a point where I only need to clean one column and leave the rest as is, is there a way to accomplished this using pandas chaining using apply or pipe.

I have tried the following which works, but I only would like to replace the dash in one specific column and leave the the rest as is since the dash in other columns is appropriate.

df = (dataFrame
    .dropna()
    .pipe(lambda x: x.replace("-", "", regex=True))

)

I have also tried this, which doesn't work since it only returns the seatnumber column.

df = (dataFrame
    .dropna()
    .pipe(lambda x: x['seatnumber'].replace("-", "", regex=True))

)

Thanks is advance.

Upvotes: 2

Views: 1072

Answers (2)

BENY
BENY

Reputation: 323226

Let us pass a dict

df = (dataFrame
    .dropna().replace({"seatnumber" : {"-":""}}, regex=True)

)

Upvotes: 0

Mustafa Aydın
Mustafa Aydın

Reputation: 18296

One way is to assign a column with the same name of the column of interest:

df = (dataFrame
      .dropna()
      .assign(seatnumber=lambda x: x.seatnumber.replace("-", "", regex=True))
)

where the dataframe at that point is passed to the lambda as x.

Upvotes: 3

Related Questions