Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - apply transformation on index of DataFrame

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.

like image 983
Baron Yugovich Avatar asked Mar 05 '23 19:03

Baron Yugovich


1 Answers

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

like image 160
EdChum Avatar answered Mar 16 '23 03:03

EdChum