Consider the data frame
c1 c2 c3
0 a 3 4 2
1 b 1 2 7
say I want to know which column in row 1 has the element 7. how will I achieve it? I am trying to achieve it using pandas.
Consider the data frame
c1 c2 c3
0 a 3 4 2
1 b 1 2 7
say I want to know which column in row 1 has the element 7. how will I achieve it? I am trying to achieve it using pandas.
If want get column of first value in row with index 1
:
a = df.loc[1].eq(7).idxmax()
print (a)
c3
Explanation:
First select column with index by loc
:
print (df.loc[1])
c1 4
c2 2
c3 7
Name: (1, b), dtype: int64
Compare with 7
:
print (df.loc[1].eq(7))
c1 False
c2 False
c3 True
Name: (1, b), dtype: bool
and for c3
get index of max value, it means first True
.
If row contains multiple values (here 7) and need all matched columns use boolean indexing
:
a = df.loc[1].eq(7)
a = a.index[a].tolist()
Not sure exactly what output you're looking for, but I believe this will help. I started by creating your dataframe.
df = pd.DataFrame({'c1':['3', '1'],
'c2':['4', '2'],
'c3':['2', '7']})
The following code reads like so: give me all the records where the column 'c3' equals 7.
df = df[df['c3'] == '7']
Output: