A one-time operation
There is a QGIS Plugin available for this purpose "Rename Field" with a simple interface. Can be found under Plugins > Rename Field > Rename field
.
A multiple-time operation
It is also a PyQGIS approach, a bit similar to what @Bera suggested.
It utilizes the renameAttributes()
method inherited from the QgsVectorDataProvider
class.
⚠️ Do not forget to backup your layer first, the code will change the layer in place.
# imports
from qgis.core import QgsProject
# getting a layer by its name
layer = QgsProject.instance().mapLayersByName("YOUR_LAYER_NAME")[0]
# accessing data provider of the layer
dp = layer.dataProvider()
# a dict to store field indexes and their new names
new_fields = {}
# looping over each field in the layer
for field in layer.fields():
name = field.name() # getting field original name
if "_" in name: # matching condition
ind = dp.fieldNameIndex(name) # finding field index
new_fields[ind] = name.replace("_", "")
# changing field names
dp.renameAttributes(new_fields)
# updating the original layer
layer.updateFields()
Note: The order of fields visualized in the attribute table might be changed.
References: