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?
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 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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With