Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row and column index of value in Pandas df

Tags:

pandas

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'      

how can I get 'column_2' and '2' by the value, 'd'? It's something similar to the opposite of .loc or .iloc.

like image 979
Chanwoo Ahn Avatar asked Sep 13 '25 00:09

Chanwoo Ahn


1 Answers

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])]

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.

like image 65
Josh Friedlander Avatar answered Sep 17 '25 21:09

Josh Friedlander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!