获取Pandas df中值的行和列索引 [英] Get row and column index of value in Pandas df
问题描述
当前,我正在尝试自动执行计划. 我将获得一个.csv文件的要求. 但是,天数按月变化,人员也偶尔变化,这意味着列数和行数不是固定的.
Currently I'm trying to automate scheduling. I'll get requirement as a .csv file. However, the number of day changes by month, and personnel also changes occasionally, which means the number of columns and rows is not fixed.
因此,我想将值"*"作为标记表示表的末尾.不幸的是,我找不到以值作为参数并返回(列表)索引(列名,行名或索引号)的函数或方法.
So, I want to put value '*' as a marker meaning end of a table. Unfortunately, I can't find a function or method that take a value as a parameter and return a(list of) index(name of column and row or index numbers).
有什么方法可以找到某个值的索引(或列表)?(例如坐标)
Is there any way that I can find a(or a list of) index of a certain value?(like coordinate)
例如,当数据框如下所示时,
for example, when the data frame is like below,
|column_1 |column_2
------------------------
1 | 'a' | 'b'
------------------------
2 | 'c' | 'd'
如何通过值"d"获得"column_2"和"2"?类似于.loc或.iloc的相反内容.
how can I get 'column_2' and '2' by the value, 'd'? It's something similar to the opposite of .loc or .iloc.
推荐答案
有趣的问题.我还使用了列表推导,但使用了np.where
.如果没有那么笨拙的方法,我仍然会感到惊讶.
Interesting question. I also used a list comprehension, but with np.where
. Still I'd be surprised if there isn't a less clunky way.
df = pd.DataFrame({'column_1':['a','c'], 'column_2':['b','d']}, index=[1,2])
[(i, np.where(df[i] == 'd')[0].tolist()) for i in list(df) if len(np.where(df[i] == 'd')[0]) > 0]
> [[('column_2', [1])]
请注意,它返回数字索引(从0开始),而不是自定义索引(从1开始).如果您有固定的偏移量,则可以在输出中添加+1
或其他内容.
Note that it returns the numeric (0-based) index, not the custom (1-based) index you have. If you have a fixed offset you could just add a +1
or whatever to the output.
这篇关于获取Pandas df中值的行和列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!