简体   繁体   中英

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']}

在此处输入图片说明

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM