Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use nested for loop and pandas's iloc to locate row and column that has 1

I am relatively new to python and pandas. I am trying to replicate a battleship game. My goal is to locate the row and column that has 1 and storage that location as the Battleship location. I created a CSV file and it looks like this

col0,col1,col2,col3,col4,col5
0,0,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0
0,1,0,0,0,0
0,0,0,0,0,0
0,0,0,0,0,0 

This is the code to read the created CSV file as a DataFrame.

import pandas 

df = pandas.read_csv('/content/pandas_tutorial/My Drive/pandas/myBattleshipmap.csv',)
print(df)

How do I use nested for loop and Pandas' iloc to locate the row and column that has 1(which is row 3 and column 1) and storage that location as the Battleship location?

I found out that a nested for loop and pandas iloc to give the entire dataframe look something like this

for x in range(len(df)):
  for y in range(len(df)):
    df.iloc[:,:]    


Do I have to put the if statement to locate the row and column?

like image 551
Loon Avatar asked Dec 06 '25 04:12

Loon


2 Answers

You really don't need to loop, you can use numpy.where:

import pandas as pd
import numpy as np

df = pd.read_csv('/content/pandas_tutorial/My Drive/pandas/myBattleshipmap.csv',)
r, c = np.where(df.astype(bool))

print(r.tolist())
print(df.columns[c].tolist())

Ouput:

[3]
['col1']

For loops like you trying...

for x in range(df.shape[0]):
    for y in range(df.shape[1]):
        if df.iloc[x, y] == 1:
            print(f'Row: {x}, Col: {df.columns[y]}')

Output:

Row: 3, Col: col1
like image 157
Scott Boston Avatar answered Dec 07 '25 18:12

Scott Boston


Use where to turn all values that are not 1 to NaN, then stack will leave you with a MultiIndex Series, whose index gives you the (row_label, col_label) tuples of everything that was 1.

df.where(df.eq(1)).stack().index
#MultiIndex([(3, 'col1')],
#           )

If you don't want the column names, perhaps get rid of the column labels. IF you only expect a single location we can grab that with .item():

df.columns = range(df.shape[1])

print(f'The Battle Ship Location is: {df.where(df.eq(1)).stack().index.item()}')
#The Battle Ship Location is: (3, 1)
like image 26
ALollz Avatar answered Dec 07 '25 18:12

ALollz