Let’s say that I have this dataframe with multi index :
JavaScript
x
14
14
1
Montant
2
IBAN Date Balance
3
FR3724687328623865 2020-09-16 654.75 -2.00
4
2020-09-17 23.65 -88.00
5
2020-09-21 1537.00 2700.20
6
2020-09-25 8346.20 -163.21
7
2020-09-28 6247.60 -468.90
8
9
FR8723498262347632 2020-10-06 13684.11 2708.00
10
FR9687234782365235 2020-10-16 4353.42 6311.00
11
2020-10-28 9641.23 562.78
12
2020-11-30 5436.95 -45.12
13
2020-09-30 4535.34 -43.56
14
How do we get access to the data in the columns “Balance” or “Date”, I do not get why that does not work :
JavaScript
1
2
1
bal = df["Montant"]["Balance"]
2
or
JavaScript
1
2
1
bal = df.loc[("Montant", "Balance")]
2
Advertisement
Answer
You should use Index.get_level_values
:
JavaScript
1
10
10
1
In [505]: df
2
Out[505]:
3
Montant
4
IBAN Date Balance
5
FR3724687328623865 2020-09-16 654.75 -2.0
6
2020-09-17 23.65 -88.00 NaN
7
2020-09-21 1537.00 2700.20 NaN
8
2020-09-25 8346.20 -163.21 NaN
9
2020-09-28 6247.60 -468.90 NaN
10
You can pass labels
:
JavaScript
1
6
1
In [509]: df.index.get_level_values('Date')
2
Out[509]: Index(['2020-09-16', '23.65', '1537.00', '8346.20', '6247.60'], dtype='object', name='Date')
3
4
In [510]: df.index.get_level_values('Balance')
5
Out[510]: Float64Index([654.75, -88.0, 2700.2, -163.21, -468.9], dtype='float64', name='Balance')
6
OR:
Pass indices
:
JavaScript
1
6
1
In [512]: df.index.get_level_values(1)
2
Out[512]: Index(['2020-09-16', '23.65', '1537.00', '8346.20', '6247.60'], dtype='object', name='Date')
3
4
In [513]: df.index.get_level_values(2)
5
Out[513]: Float64Index([654.75, -88.0, 2700.2, -163.21, -468.9], dtype='float64', name='Balance')
6