Reputation: 455
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']}
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:
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
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