gpt4 book ai didi

python - 获取 pandas 数据对象的 x,y 样式坐标

转载 作者:行者123 更新时间:2023-11-30 22:21:51 24 4
gpt4 key购买 nike

我想知道是否可以在 pandas 数据框中搜索值,如果找到,则返回行、列名称样式坐标。例如,如果在下面的数据帧中搜索 mat 字符串,则将返回 (3, C)。

     A    B    C
0 20 32 bat
1 30 234 cat
2 10 23 rat
3 40 23 mat
4 50 42523 etc

我已经通读了文档,我发现的最接近的解决方案是 index.get_loc() ,尽管这只返回基于命名索引的 loc

Pandas 版本0.22.0

最佳答案

正如 @Wen 所建议的,np.where 是搜索值坐标的有效方法。下面的方法将返回此类坐标的列表。

import pandas as pd

df = pd.DataFrame([[20, 32, 'bat'], [30, 234, 'cat'],
[10, 23, 'rat'], [40, 23, 'mat'],
[50, 42523, 'etc']], columns=['A', 'B', 'C'])

[(x, df.columns[y]) for x, y in zip(*np.where(df.values == 'mat'))] # [(3, 'C')]

关于python - 获取 pandas 数据对象的 x,y 样式坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com