I am having difficulty finding the unique multi index tuple of my dataframe.
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,100,size=(100, 5)), columns=list('ABCDF'))
df = df.set_index(['A','B','C'])
print(df)
I need to find the nth row index i.e. the values in A,B,C.
This tuple which I pick up will then be used to query a separate df which appears to be working fine.
Any help would be appreciated
CodePudding user response:
You can use:
df.index[n]
Example for the fifth (n=4) row:
(81, 37, 25)
CodePudding user response:
@MatthewHooper, for getting the value of nth index in pandas use the index method for getting the values of nth columns use iloc method For example
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100,5)), columns=list('ABCDF'))
# Set index using column
df = df.set_index(['A','B','C'])
Print the 5 first values
print(df.head(5))
Output
D F
A B C
19 32 44 43 94
32 1 76 79 4
2 96 76 80 77
68 67 42 87 50
20 68 14 4 9
Find the 4th row index
print(df.index[4])
Output
(20, 68, 14)
Find the 4th columns values
print(tuple(df.iloc[4]))
Output
(4, 9)
