I wrote a short code to illustrate what's confusing me:
import numpy as np
import pandas as pd
a = [0.2,0.4]
f = np.linspace(0.0,4.0,5)
mindex = pd.MultiIndex.from_product([a,f], names=['a', 'f'])
df = pd.DataFrame(dtype=float, index=range(0,100), columns=mindex)
For the printed structure of the DataFrame, see the EDIT. Now, I want to know how to specifically use .loc
to assign a value to a specific element. Apparently, the following:
print(df.loc[0, 0.2, 0.0])
gives the me error:
pandas.core.indexing.IndexingError: Too many indexers
but I don't understand why? The following two statements work as expected:
print(df.loc[0])
print(df.loc[0,0.2])
with print(df.loc[0,0.2])
for example outputting:
f
0.0 NaN
1.0 NaN
2.0 NaN
3.0 NaN
4.0 NaN
Name: 0, dtype: float64
But how to I get that final f=0.0
value out?
Also, my next idea would have been to use a tuple for the column index, but print(df.loc[0,[0.2,0.0]])
doesn't work either.
EDIT: Just to clarify the structure of my DataFrame.
print(df)
gives:
a 0.2 0.4
f 0.0 1.0 2.0 3.0 4.0 0.0 1.0 2.0 3.0 4.0
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
...
...
EDIT 2: Just to update after the comments, basically two suggestions were to use df.loc[0][0.2][0.0]
or df[[(0.2,0.0)]].loc[0]
. However, since I need this to assign values to specific elements, both of those seem to be discouraged by pandas (see http://pandas.pydata.org/pandas-docs/stable/indexing.html#returning-a-view-versus-a-copy).
In fact, df.loc[0][0.2][0.0] = 2
seems to work, but df[[(0.2,0.0)]].loc[0] = 2
doesn't (because it returns a copy of a slice instead of a view).