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.
(1) IF condition – Set of numbers Suppose that you created a DataFrame in Python that has 10 numbers (from 1 to 10). You then want to apply the following IF conditions: If the number is equal or lower than 4, then assign the value of 'True' Otherwise, if the number is greater than 4, then assign the value of 'False'
DataFrame - apply() function The apply() function is used to apply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame's index (axis=0) or the DataFrame's columns (axis=1).
Use DataFrame. apply() to Apply the if-else Condition in a Pandas DataFrame in Python. The apply() method uses the data frame's axis (row or column) to apply a function. We can make our defined function that consists of if-else conditions and apply it to the Pandas dataframe.
Your one-liner
df.applymap(lambda x: x.upper() if isinstance(x, str) else x)
A B
0 1 A
1 B 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With