I wondered how to easy access the column index for a specific cell in pandas.
E.g. if i got this dataframe:
df = pd.DataFrame.from_dict({0:['01_CF56_1'], 1:['05_CF41_3'], 2:['06_CF44_2']})
i'd like to have a function that gives me
f('05_CF41_3') => 1
because this value is in the column index 1 (I don't care about the row)
of course the naive way would be to go through all rows and columns and match the cell contents, but i wonder if there is a more elegant solution
You could use the second element of indices to get the column indices and use it in where
. Then find the first valid column index using argmax
:
np.argmax(np.where(df == '05_CF41_3', np.indices(df.shape)[1], -1) >= 0)
returns 1
.
If the searched for value may occur in multiple columns you could use something like that to get a list of all column numbers where this value occurs:
a = np.where(df == '05_CF41_3', np.indices(df.shape)[1], -1)
list(set(a[a>=0]))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments