首页 > 解决方案 > 如何使用嵌套的 for 循环和 pandas 的 iloc 来定位具有 1 的行和列

问题描述

我对 python 和 pandas 比较陌生。我正在尝试复制战舰游戏。我的目标是找到具有 1 的行和列并将该位置存储为战舰位置。我创建了一个 CSV 文件,它看起来像这样

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 

这是将创建的 CSV 文件作为 DataFrame 读取的代码。

import pandas 

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

如何使用嵌套的 for 循环和 Pandas 的 iloc 来定位具有 1 的行和列(即第 3 行和第 1 列)并将该位置存储为战舰位置?

我发现嵌套的 for 循环和 pandas iloc 使整个数据框看起来像这样

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


我是否必须放置 if 语句来定位行和列?

标签: pythonpandasdataframe

解决方案


你真的不需要循环,你可以使用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())

输出:

[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]}')

输出:

Row: 3, Col: col1

推荐阅读