Reputation: 37
I've been searching around for a while now, but I can't seem to find the answer to this small problem.
I have this code to make a function uppercase for values string:
import pandas as pd
import numpy as np
df1 = {'Name':['Tom', 'nick', 'krish', 'jack','elo'],
'Alpha':['Arizona AZ asdf hello abc','Georgia GG asdfg hello def','Newyork NY asdfg hello ghi','Indiana IN asdfg hello jkl','Florida FL ASDFG hello mno'],
'Naise':['hello abc','hello def','hello ghi','hello jkl','hello mno'],
'Helo':['sample al','sample bel', 'sample cel', 'sample del', 'sample el'],
'Food':['chicken','pizza','rice','ice cream','bakwan'],
'Age':[11,12,13,17,29]
}
df1 = pd.DataFrame(df1)
df1
def upper_consistent(df):
df = df.apply(lambda x: x.str.upper() if x.dtype == "object" else x)
return df
and I'm trying to apply the function to uppercase the two columns only
df1[['Name', 'Naise']] = df1[['Name', 'Naise']].apply(upper_consistent)
but i get error:
AttributeError: 'str' object has no attribute 'dtype'
how do i get the result according to the desired output?
Upvotes: 1
Views: 5119
Reputation: 120391
If your function receive a dataframe as parameter, don't use apply
but call your function with your dataframe as parameter:
def upper_consistent(df):
df = df.apply(lambda x: x.str.upper() if x.dtype == "object" else x)
return df
df1[['Name', 'Naise']] = upper_consistent(df1[['Name', 'Naise']])
Output:
>>> df1
Name Alpha Naise Helo Food Age
0 TOM Arizona AZ asdf hello abc HELLO ABC sample al chicken 11
1 NICK Georgia GG asdfg hello def HELLO DEF sample bel pizza 12
2 KRISH Newyork NY asdfg hello ghi HELLO GHI sample cel rice 13
3 JACK Indiana IN asdfg hello jkl HELLO JKL sample del ice cream 17
4 ELO Florida FL ASDFG hello mno HELLO MNO sample el bakwan 29
Upvotes: 0
Reputation:
Why not just apply .str.upper()
to each column with a lambda function?
df1[['Name', 'Naise']] = df1[['Name', 'Naise']].astype(str).apply(lambda col: col.str.upper())
Upvotes: 4