Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply with a condition on a Pandas dataframe elementwise

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.

like image 763
gk7 Avatar asked Jan 21 '17 22:01

gk7


People also ask

How do you apply a condition to a DataFrame in Python?

(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'

How do I apply a function to a DataFrame in pandas?

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).

How do I apply if else condition for a column in pandas?

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.


1 Answers

Your one-liner

df.applymap(lambda x: x.upper() if isinstance(x, str) else x)

   A  B
0  1  A
1  B  2
like image 56
piRSquared Avatar answered Oct 20 '22 01:10

piRSquared