Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all str type elements in a pd.DataFrame

Based on my little knowledge on pandaspandas.Series.str.contains can search a specific str in pd.Series. But what if the dataframe is large and I just want to glance all kinds of str element in it before I do anything?

Example like this:

pd.DataFrame({'x1':[1,2,3,'+'],'x2':[2,'a','c','this is']})
    x1  x2
0   1   2
1   2   a
2   3   c
3   +   this is

I need a function to return ['+','a','c','this is']

like image 594
Garvey Avatar asked Dec 24 '22 08:12

Garvey


1 Answers

If you are looking strictly at what are string values and performance is not a concern, then this is a very simple answer.

df.where(df.applymap(type).eq(str)).stack().tolist()

['a', 'c', '+', 'this is']
like image 141
piRSquared Avatar answered Feb 09 '23 02:02

piRSquared