Reputation: 155
I am learning Python and I try to understand how apply() method works in Pandas dataframes.
As an exercise I would like to use a one line code to apply the str.upper() method on the elements of a Pandas dataframe only if these elements are strings.
I thought to combine a lambda conditional expression with apply but the problem is that when apply calls the Pandas dataframe, the dataframe --if I have understood well -- returns a Series to apply which then passes it to the function. I wonder how I could get a level deeper and call the function on the elements of the Pandas dataframe.
This is how I do what I intend when apply() calls on a column of the DataFrame (a Series):
df= pd.DataFrame([[1, 'a'],['b',2]], columns = ['A', 'B'] )
df['A'].apply(lambda x: str.upper(x) if type(x) is str else x)
But how I could do that on the entire dataframe with one line of code?
I am looking for a solution that would work with columns that contain both numerics and strings and would leave the numerics intact.
Upvotes: 8
Views: 11815
Reputation: 294218
Your one-liner
df.applymap(lambda x: x.upper() if isinstance(x, str) else x)
A B
0 1 A
1 B 2
Upvotes: 8