4

This is my code

import pandas as pd
x = pd.DataFrame.from_dict({'A':[1,2,3,4,5,6], 'B':[10, 20, 30, 44, 48, 81]})
a = x['A'].apply(lambda t: t%2==0) # works
c = x.index.apply(lambda t: t%2==0) # error

How can I make that code work in the easiest way? I know how to reset_index() and then treat it as a column, but I was curious if it's possible to operate on the index as if it's a regular column.

EdChum
  • 376,765
  • 198
  • 813
  • 562
Baron Yugovich
  • 3,843
  • 12
  • 48
  • 76

3 Answers3

4

You have to convert the Index to a Series using to_series:

c = x.index.to_series().apply(lambda t: t%2==0)

if you want to call apply as Index objects have no apply method

There are a limited number of methods and operations for an Index: http://pandas.pydata.org/pandas-docs/stable/api.html#modifying-and-computations

EdChum
  • 376,765
  • 198
  • 813
  • 562
2

Pandas hasn't implemented pd.Index.apply. You can, for simple calculations, use the underlying NumPy array:

c = x.index.values % 2 == 0

As opposed to lambda-based solutions, this takes advantage of vectorised operations.

jpp
  • 159,742
  • 34
  • 281
  • 339
1

Pandas index have a map method:

c = x.index.map(lambda t: t%2==0)   # Index([True, False, True, False, True, False], dtype='object')

Note that this returns a Index, not a pandas Series.

FLab
  • 7,136
  • 5
  • 36
  • 69