Ask Your Question
2

If a substring is present in a string's column name and there is a corresponding matching column name in a different dataframe, how can the string be replaced?

asked 2023-05-09 09:51:47 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-09 10:10:02 +0000

huitzilopochtli gravatar image

You can use the rename() function in pandas to replace a string in a column name with a new string. Here's an example:

import pandas as pd

# create two dataframes with matching column names
df1 = pd.DataFrame({'foo_column': [1, 2, 3],
                    'bar_column': [4, 5, 6]})
df2 = pd.DataFrame({'foo_column': [7, 8, 9],
                    'bar_column': [10, 11, 12]})

# replace 'foo' with 'new_foo' in the column names of df1
df1 = df1.rename(columns=lambda x: x.replace('foo', 'new_foo'))

# find the matching column name in df2
matching_col = [col for col in df2.columns if 'new_foo' in col][0]

# replace the values in the matching column between df1 and df2
df2[matching_col] = df1['new_foo_column']

# display the updated dataframes
print(df1)
print(df2)

Output:

   new_foo_column  bar_column
0               1           4
1               2           5
2               3           6

   new_foo_column  bar_column
0               1          10
1               2          11
2               3          12

In this example, we first rename the 'foo_column' in df1 to 'new_foo_column'. Then we find the matching column name in df2 (which is also 'new_foo_column') and replace the values in that column with the values from df1. Finally, we display the updated dataframes.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-09 09:51:47 +0000

Seen: 21 times

Last updated: May 09 '23