You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas多级索引列合并代码:为何'{0[0]}|{0[1]}'.format可行而另一种写法报错?

Why You're Getting "TypeError: 'str' object is not callable" & How to Fix It

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 format function itself to map:
    df.columns = df.columns.map('{0[0]}|{0[1]}'.format)
    
  • What you attempted was calling format immediately and passing the resulting string to map (likely in a line like df.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:

  1. df.columns is a multi-level index, so each entry is a tuple (e.g., ('index1', 'subindex1')).
  2. '{0[0]}|{0[1]}'.format refers to the format method bound to that string template. This is a callable function that accepts one argument (the tuple from the index).
  3. When map runs, it passes each index tuple to this format function:
    • For the tuple ('index1', 'subindex1'), {0[0]} grabs the first element ('index1'), {0[1]} grabs the second ('subindex1'), and they're joined with |.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:53:49