To rename columns in pandas dataframe using str.contains
and if
statements in Python:
str.contains
.rename(columns)
function.Here's an example code:
main.py467 chars15 lines
Output:
main.py116 chars5 lines
In this example, the code renames columns that contain ABC_x
, DEF_y
, and GHI_z
with New_ABC
, New_DEF
, and New_GHI
respectively. df.columns.str.contains()
function checks if the specified string is present in any column names. If the condition is true, rename()
function renames the column with the new name.
gistlibby LogSnag