英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论