Pandas多级索引列合并代码:为何'{0[0]}|{0[1]}'.format可行而另一种写法报错?
Hey there, let's break down exactly what's happening here and why your approach is throwing that error.
The Root Cause of the Error
First, let's clarify the critical difference between the working solution and what you tried:
- The correct Pythonic code passes the
formatfunction itself tomap:df.columns = df.columns.map('{0[0]}|{0[1]}'.format) - What you attempted was calling
formatimmediately and passing the resulting string tomap(likely in a line likedf.columns.map('{}|{}'.format([0],[1]))), which is what triggered the error.
Here's why that breaks:
When you run '{}|{}'.format([0],[1]), you're executing the format call right away, which returns a plain string like '[0]|[1]'. The map function expects a callable function that it can run on each element of df.columns (each element is a tuple from your multi-level index). When you pass a string instead of a function, map tries to "call" that string with each index tuple as an argument—hence the error: a string isn't a callable function.
How the Correct Approach Works
Let's unpack the working code step by step:
df.columnsis a multi-level index, so each entry is a tuple (e.g.,('index1', 'subindex1')).'{0[0]}|{0[1]}'.formatrefers to theformatmethod bound to that string template. This is a callable function that accepts one argument (the tuple from the index).- When
mapruns, it passes each index tuple to thisformatfunction:- For the tuple
('index1', 'subindex1'),{0[0]}grabs the first element ('index1'),{0[1]}grabs the second ('subindex1'), and they're joined with|.
- For the tuple
A More Readable Alternative
If the {0[0]} syntax feels confusing, you can use a lambda function instead—it does the same thing but is more explicit:
df.columns = df.columns.map(lambda col_tuple: f"{col_tuple[0]}|{col_tuple[1]}")
This lambda takes each index tuple directly, extracts its two elements, and joins them with | using an f-string.
内容的提问来源于stack exchange,提问作者Zac

