SaCvP
SaCvP

Reputation: 455

Python - Pandas - Replace a string from a column based on the value from other column

I've a dataframe with the following data:

d = {'col0': ['Table 1', 'Table 2'], 'col1': ['Tablename: Table 1', 'Tablename: Table 2'], 'col2': ['Table A', 'Table B']}

enter image description here

What I am trying is to replace on col2 the values that exists on col0 with the values from col2.

Basically my output it will be this:

enter image description here

I was trying to make a simple replace such as:

df['col3'] = df['col1'].replace(df.col0, df['col2'], regex = True)
print(df)

But it gives me "TypeError: replace() takes no keyword arguments"

Then I try this:

df['col3'] = df['col1'].replace(df.col0, str(df['col2']), regex = True)
print(df)

But it gives me a list on col3...

How can I do that?

Thanks

Upvotes: 0

Views: 205

Answers (1)

Yuna A.
Yuna A.

Reputation: 149

You have to pass a list or something list-like to the first and second parameters of replace. .values turns df['col0'] and df['col2'] into numpy arrays which will work.

df['col3'] = df['col1'].replace(df['col0'].values, df['col2'].values, regex = True)

Output:

      col0                col1     col2                col3
0  Table 1  Tablename: Table 1  Table A  Tablename: Table A
1  Table 2  Tablename: Table 2  Table B  Tablename: Table B

You can see the full documentation of pd.DataFrame.replace here.

Upvotes: 1

Related Questions