I have a pandas dataframe :
data = {'id': [1,1,2,3],
'name': ["Noemie","Elena", "Lize", "Patrick"],
'value': ["pink", "blue", "red", "yellow" ]}
So I gather all the rows with the id "1" thanks to df.set_index(["id","name"])
My columns id and name become indexes, I wonder if is it possible to get for example the value "Noemie"
Knowing that, before multi-indexing I can have it with
df.loc[0].at["name"]
CodePudding user response:
You can use df.index.get_level_values
to get the desired index column you want and do comparison.
df[df.index.get_level_values('name') == 'Noemie']
value
id name
1 Noemie pink
Or if you just want the index value
df.index[df.index.get_level_values('name') == 'Noemie'][0][1]
Out[30]: 'Noemie'
CodePudding user response:
If need select first row by DataFrame.iloc
then get second value of indices by name[1]
- python count from 0
:
data = {'id': [1,1,2,3],
'name': ["Noemie","Elena", "Lize", "Patrick"],
'value': ["pink", "blue", "red", "yellow" ]}
df = pd.DataFrame(data).set_index(["id","name"])
print (df.iloc[0])
value pink
Name: (1, Noemie), dtype: object
print (df.iloc[0].name)
(1, 'Noemie')
out = df.iloc[0].name[1]
print (out)
Noemie
For select second row:
print (df.iloc[1])
value blue
Name: (1, Elena), dtype: object
print (df.iloc[1].name)
(1, 'Elena')
out = df.iloc[1].name[1]
print (out)
Elena
EDIT: If need all values of index if id=1
use:
print (df.loc[1])
value
name
Noemie pink
Elena blue
s = df.loc[1].index.tolist()
print (s)
['Noemie', 'Elena']