在pandas数据框中查找元素的确切位置。

huangapple go评论76阅读模式
英文:

Find the exact location of an element in pandas dataframe

问题

我有以下的pandas数据框:

df = pd.DataFrame({"A": [1,2,3], "B": [-2,8,1], "C": [-451,23,326]})

是否有函数可以返回元素的确切位置?假设元素存在于表格中且没有重复。例如,如果element = 326,那么它将返回行:2 列:2。非常感谢。

英文:

I have the following pandas dataframe:

df = pd.DataFrame({"A": [1,2,3], "B": [-2,8,1], "C": [-451,23,326]})

Is there any function that returns the exact location of an element? Assuming that the element exists in the table and no duplicate. E.g. if element = 326 then it will return row:2 col:2.
Many thanks

答案1

得分: 4

你可以使用stack

element = 326

s = df.stack().eq(element)

out = s
展开收缩
.index.tolist()

输出:[(2, 'C')]

或者使用numpy.where

import numpy as np

# 作为位置
idx, col = np.where(df.eq(element))
# (array([2]), array([2]))

# 作为标签
df.index[idx], df.columns[col]
# (Int64Index([2], dtype='int64'), Index(['C'], dtype='object'))
英文:

You can use stack:

element = 326

s = df.stack().eq(element)

out = s
展开收缩
.index.tolist()

Output: [(2, 'C')]

Or numpy.where:

import numpy as np

# as positions
idx, col = np.where(df.eq(element))
# (array([2]), array([2]))

# as labels
df.index[idx], df.columns[col]
# (Int64Index([2], dtype='int64'), Index(['C'], dtype='object'))

答案2

得分: 1

你可以使用np.where结合df.values

element = 326

indices = np.where(df.values == element)

row_index, col_index = indices[0][0], indices[1][0]

print("行:", row_index)
print("列:", col_index)

输出:

 2
 2
英文:

You can use np.where combined with df.values:

element = 326

indices = np.where(df.values == element)

row_index, col_index = indices[0][0], indices[1][0]

print("Row:", row_index)
print("Column:", col_index)

Output:

Row: 2
Column: 2

huangapple
  • 本文由 发表于 2023年5月23日 01:09:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76308496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定