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.
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
Asked: 2023-05-09 09:51:47 +0000
Seen: 21 times
Last updated: May 09 '23
How can you use linq to choose a specific column from a datatable?
When attempting to write a Spark dataset to a Hive table, why is it unable to locate the column?
How can I include the hours component to a DateTime column using PowerQuery?
Identify commonalities among the strings in a specific column of a DataFrame.