Flatten multindex column in a pipe in pandas
Suppose I have the following DataFrame:
arrays = [[1, 1, 2, 2], ["red", "blue", "red", "blue"]]
ix = pd.MultiIndex.from_arrays(arrays, names=("number", "color"))
df = pd.DataFrame([[10, 20, 30, 40], [50, 60, 70, 80]], columns=ix)
df

I would like to flatten the MultiIndex column like that:
df.columns = [str(x[0])+"_"+str(x[1]) for x in df.columns]
df

But I would like to do it in a pipe.
For instance, supposing the function rename_columns would exist (it doesn't), it would look like:
df.rename_columns(lambda x: str(x[0])+"_"+str(x[1]))
Said otherwise, I would like to write that rename_columns function.
How can I achieve this?
EDIT: The rename function doesn't work:
df.rename(lambda x: str(x[0])+"_"+str(x[1]))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[28], line 1
----> 1 df.rename(lambda x: str(x[0])+"_"+str(x[1]))
File .venv\Lib\site-packages\pandas\core\frame.py:6471, in DataFrame.rename(self, mapper, index, columns, axis, copy, inplace, level, errors)
6352 """
6353 Rename columns or index labels.
6354
(...) 6468 4 3 6
6469 """
6470 self._check_copy_deprecation(copy)
-> 6471 return super()._rename(
6472 mapper=mapper,
6473 index=index,
6474 columns=columns,
6475 axis=axis,
6476 inplace=inplace,
6477 level=level,
6478 errors=errors,
6479 )
File .venv\Lib\site-packages\pandas\core\generic.py:1065, in NDFrame._rename(self, mapper, index, columns, axis, inplace, level, errors)
1058 missing_labels = [
1059 label
1060 for index, label in enumerate(replacements)
1061 if indexer[index] == -1
1062 ]
1063 raise KeyError(f"{missing_labels} not found in axis")
-> 1065 new_index = ax._transform_index(f, level=level)
1066 result._set_axis_nocheck(new_index, axis=axis_no, inplace=True)
1068 if inplace:
File .venv\Lib\site-packages\pandas\core\indexes\base.py:6672, in Index._transform_index(self, func, level)
6670 return type(self).from_arrays(values)
6671 else:
-> 6672 items = [func(x) for x in self]
6673 return Index(items, name=self.name, tupleize_cols=False)
Cell In[28], line 1
----> 1 df.rename(lambda x: str(x[0])+"_"+str(x[1]))
TypeError: 'int' object is not subscriptable