python - 如何使用嵌套的 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 语句来定位行和列?
解决方案
你真的不需要循环,你可以使用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
推荐阅读
- swift - 如何删除 Core Data SwiftUI?
- kubernetes - 离线 git clone Drone CI 使用代理作为 Nexus
- php - ACF 自定义块 get_field() 在前端显示 null?
- sockets - Socket.io 4.x - 如何获取用户作为用户名列表?
- django - 使用 ForeignKey、Django Subquery 和 OuterRef 将一个模型中的字段合并到另一个模型中
- ffmpeg - ffmpeg:通过添加黑框将纵向和横向视频文件合并到一个文件中
- jquery - 为什么我的 jquery 代码在移动设备上不起作用?
- swiftui - SwiftUI:LazyVGrid 滚动时不刷新
- javascript - 如何在单选按钮上使用 JavaScript 逻辑?
- php - 统计通过分数的用户