alex
alex

Reputation: 2541

python pandas get column which has first element containing a string

So i've got this DataFrame:

df = pd.DataFrame({'A': ['ex1|context1', 1, 'ex3|context3', 3], 'B': [5, 'ex2|context2', 6, 'data']})

i want to get the column that has '|' in its first element which in my example would be A because ex1|context1 is the first element and contains '|'

Upvotes: 2

Views: 855

Answers (1)

jezrael
jezrael

Reputation: 862661

If always exist at least one | value in data:

s = df.stack().reset_index(level=0, drop=True) 
out = s.str.contains('|', na=False).idxmax()
print (out)
A

General solution working also if no data match:

df = pd.DataFrame({'A': ['ex1context1', 1, 'ex3ontext3', 3], 
                   'B': [5, 'ex2ontext2', 6, 'data']})
print (df)
             B           A
0  ex1context1           5
1            1  ex2ontext2
2   ex3ontext3           6
3            3        data

s = df.stack().reset_index(level=0, drop=True)

out = next(iter(s.index[s.str.contains('|', na=False, regex=False)]), 'no match')
print (out)
no match

Upvotes: 3

Related Questions