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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With