0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.