Reputation: 1071
I have an output table for my python script which, depending on the month can have a single record with none value or multiple records with proper values. My code converts the salary amount to $ and , format. But if there is a None in the Salary column this won't work. How can I convert this salary column conditionally? I have provided sample data and what I tried so far.
sample data
d1 = {'name': ['john', 'tom'], 'Address': ['NY', 'CA'], 'Salary' : ['5000', '6000']}
df1 = pd.DataFrame(data = d1)
my code
if df1['Salary'] is None:
pass
else:
df1['Salary'] = df1['Salary'].astype(int)
df1['Salary'] = df1.apply(lambda x: "${:,}".format(x['Salary']), axis=1)
This is the output I want
Address Salary name
0 NY $5,000 john
1 CA $6,000 tom
But if the salary column has None in it then this code doesn't work.
d2 = {'name': ['john', 'tom'], 'Address': ['NY', 'CA'], 'Salary' : ['5000', None]}
df2 = pd.DataFrame(data = d2)
I get the following error:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
I understand the error, a column can not be simultaneously integer and also have None in it, let alone the formatted value. How can I get the output I am looking for even if there is None value in my column ?
Upvotes: 1
Views: 73
Reputation: 3353
Only apply the function to the value in the column that are not None:
d2 = {'name': ['john', 'tom'], 'Address': ['NY', 'CA'], 'Salary' : ['5000', None]}
df2 = pd.DataFrame(data = d2)
df2.loc[df2['Salary'].notnull(), 'Salary'] = (df2.loc[df2['Salary'].notnull(), 'Salary']
.apply(lambda x: "${:,}".format(int(x))))
# name Address Salary
# 0 john NY $5,000
# 1 tom CA None
Upvotes: 2