0

I came across this very helpful answer to a question that I had about merging multilevel indexed columns into a single level (Pandas dataframe with multiindex column - merge levels), and one of the pythonic ways that was suggested was to use this particular line of code,

df.columns = df.columns.map('{0[0]}|{0[1]}'.format) 

where df is the dataframe with multilevel indexed columns.

It basically converted columns into

index1|subindex1  index1|subindex2  index1|subindex3  index2|subindex1
1                 1                 2                 5
2                 1                 2                 4

and so on.

My question is whether someone can explain to me why writing '{0[0]}|{0[1]}'.format works but when I tried writing '{}|{}'.format([0],[1]), I get a type error.

TypeError: 'str' object is not callable

Thank you!

Zac
  • 329
  • 1
  • 3
  • 8
  • 1
    Try `'{0[0]}|{0[1]}'.format(['index1', 'subindex1'])` as a working example, and read [the docs on `str.format`](https://docs.python.org/3/library/stdtypes.html#str.format). – jonrsharpe Jan 22 '18 at 15:56
  • 2
    `'{0[0]}|{0[1]}'.format` is a function (or, more accurately, a method). `'{}|{}'.format([0],[1])` is not a function, it's a function call that returns a string. Obviously, you can't pass a string to the `map` function. – Aran-Fey Jan 22 '18 at 15:57

0 Answers0