Can I access to DataFrame index and use it when calculating something in python?

44 Views Asked by At

I'm reading the data I'm working on and making it organized with the following codes.

import pandas as pd
df = pd.read_csv("data.csv").assign(date=lambda x: pd.to_datetime(x['date']))
.groupby([pd.Grouper(key='date', freq='M'), pd.Grouper(key='item_id')]).count().reset_index()
.pivot('date', 'item_id').fillna(0).astype(int)

This way I can see the indexes and their values.

output

What should I do if I want to operate using the values in the indexes? How can I access them?

1

There are 1 best solutions below

2
On BEST ANSWER

You can treat your index as a normal column:

df['new_column'] = df.index

Or

df = df.reset_index(drop=False)