1
import pandas as pd
import numpy as np
import string
df = pd.DataFrame(np.arange(12).reshape(3,4), index = list('abc'), columns = list('wxyz'))
df
   w  x   y   z
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11

I know that I can change the index using the map method in this way.

df.index.map(str.upper)

Wondered if I could change the Index in this way.

df.index.map(string.ascii_lowercase)    

But, when I ran the code, I got the following error

TypeError: 'str' object is not callable

Can someone explain the syntactical difference and the reason for the error.

jpp
  • 159,742
  • 34
  • 281
  • 339
vivek
  • 563
  • 7
  • 16
  • 4
    `string.ascii_lowercase` is not a function, it's just a string with `'abcdefghijklmnopqrstuvwxyz'` value – Zero Jul 25 '18 at 08:08
  • 2
    What are you trying to achieve in the second one? An upper case to lower case mapping? – ayhan Jul 25 '18 at 08:10

2 Answers2

0

There is no syntactical difference. There is a difference in the type of object you are using as a parameter to pandas.Index.map. The docs make clear what's permitted:

Index.map(mapper)
    Apply mapper function to an index.

mapper : callable
   Function to be applied.

In general, it's a better idea to test whether an object is callable than to test whether it's a function. See What is duck typing? for the rationale.

In this case, str.upper is a callable, while string.ascii_lowercase is a string. To confirm this, you can use callable (Python 3.2+):

callable(str.upper)               # True
callable(string.ascii_lowercase)  # False
jpp
  • 159,742
  • 34
  • 281
  • 339
0

The string package is mostly deprecated.

import string 

string.__doc__

"A collection of string operations (most are no longer used).
\n\nWarning: most of the code you see here isn't normally used nowadays [...]

The builtin str allows you to do most operations. As stated by Zero string.ascii_lowercase just gives you the alphabet in lowercase.

If what you want to achieve is to put your DataFrame index in lowercase, then you should do df.index.map(str.lower).

import pandas as pd
import numpy as np
import string
df = pd.DataFrame(np.arange(12).reshape(3,4), index = list('ABC'), columns = list('wxyz'))
df.index.map(str.lower)
   w  x   y   z
a  0  1   2   3
b  4  5   6   7
c  8  9  10  11
Adrien Pacifico
  • 1,649
  • 1
  • 15
  • 33