Home > other >  Using Loc and Iloc together
Using Loc and Iloc together

Time:06-14

Hello I am trying to pull three rows of data. Row 0 Row 1 and the Row that is titled "Inventories".

I Figured the best way would be to find the Row number of Inventories and parse the date using iloc. However I get an error that says to many indexers. Any help would be appreciated

df.columns=df.iloc[1]
cols = df.columns.tolist()
A =df.loc[df[cols[0]].isin(['Inventories'])].index.tolist()
df = df.iloc[[0,1,[A]]]

I have also tried

df = df.iloc[[0,1,A]]

Also please note A returns 56, and if I replace A with 56 in

df = df.iloc[[0,1,56]] 

I get the desired outcome.

Any help would be appreciated.

CodePudding user response:

For position of matched condition use Series.argmax, so possible add A without [] to DataFrame.iloc, it working well if ALWAYS match condition:

A = df[cols[0]].eq('Inventories').argmax()
df = df.iloc[[0,1,A]]

Another idea is add conditio with bitwise OR by | for test first 2 rows:

df = pd.DataFrame({'col' : [100,10,'s','Inventories',1,10,100]})
df.index  = 10
    
print (df)
            col
10          100
11           10
12            s
13  Inventories
14            1
15           10
16          100


df = df[np.in1d(np.arange(len(df)), [0,1]) | df.iloc[:, 0].eq('Inventories')]
print (df)
            col
10          100
11           10
13  Inventories

Or join filtered rows by positions and by condition:

df = pd.concat([df.iloc[[0, 1]], df[df.iloc[:, 0].eq('Inventories')]])
print (df)
            col
10          100
11           10
13  Inventories

CodePudding user response:

IIC you are wanting to pull out 3 specific values in the index (which can be an index number or a string). This will allow you to set the values you want to pull back when referencing an index.

df = pd.DataFrame({
    'Column' : [1, 2, 3, 4, 5],
    'index' : [0, 1, 'Test', 'Inventories', 4]
})
df = df.set_index('index')
df.loc[[0, 1, 'Inventories']]
  • Related