I have a issue with applying function for column in pandas, please see below code :
JavaScript
x
21
21
1
import pandas as pd
2
3
#create a dict as below
4
data_dic = {
5
"text": ['hello',1,'how are you?',4],
6
"odd": [0,2,4,6],
7
"even": [1,3,5,7]
8
}
9
#create a DataFrame
10
df = pd.DataFrame(data_dic)
11
#define function
12
def checktext(str1):
13
if isinstance(str1,str):
14
return str1.upper()
15
def checknum(str1):
16
if isinstance(str1,int):
17
return str1+1
18
19
df['new'] = df['text'].apply(lambda x: checktext(x))
20
df['new'].head()
21
my df now show like below:
JavaScript
1
6
1
text odd even new
2
0 hello 0 1 HELLO
3
1 1 2 3 None
4
2 how are you? 4 5 HOW ARE YOU?
5
3 4 6 7 None
6
I would like to apply function checknum for 2 cell in column ‘new’ which is having ‘None’ value. Can someone assist this ? Thank you
Advertisement
Answer
IIUC, you can use vectorial code:
JavaScript
1
5
1
# make string UPPER
2
s = df['text'].str.upper()
3
# where there was no string, get number + 1 instead
4
df['new'] = s.fillna(df['text'].where(s.isna())+1)
5
output:
JavaScript
1
6
1
text odd even new
2
0 hello 0 1 HELLO
3
1 1 2 3 2
4
2 how are you? 4 5 HOW ARE YOU?
5
3 4 6 7 5
6
That said, for the sake of the argument, your 2 functions could be combined into one:
JavaScript
1
8
1
def check(str1):
2
if isinstance(str1,str):
3
return str1.upper()
4
elif isinstance(str1,int):
5
return str1+1
6
7
df['new'] = df['text'].apply(check)
8