clattenburg cake
clattenburg cake

Reputation: 1222

Convert Pandas Dataframe Strings to Decimal (Inc. Empty Strings)

I have written a utility function that will convert strings to decimals- it also returns a zero decimal if the string is empty.

from decimal import * 

def convert_string_to_decimal(some_string):
    return Decimal('0.00') if (some_string == '' or some_string.isspace()) else Decimal(some_string)

I have a pandas dataframe of a bank statement with two columns that I would now like to convert to decimals. They are called debit and credit. How best should I go about using the function above? Secondly, is this even recommended? I read somewhere that one should use Decimal for currency.

Upvotes: 1

Views: 4315

Answers (1)

d r
d r

Reputation: 7776

There is no need for new function, you can do it with astype...

import pandas as pd

data = {'id': ['A', 'B', 'C', 'D', 'E'], 'debit': ['1.11','', '2.22', '3.33', ' '], 'credit': ['1.2345', '2.3456', '3.00', '4', '5']}
df = pd.DataFrame(data)
print(df)
'''
  id debit credit
0  A  1.11      1
1  B            2
2  C  2.22      3
3  D  3.33      4
4  E            5
'''
df['debit'] = df['debit'].replace(' ', '').replace('', '0.00').astype(float)
df['credit'] = df['credit'].replace(' ', '').replace('', '0.00').astype(float)
print(df)
'''
  id  debit  credit
0  A   1.11  1.2345
1  B   0.00  2.3456
2  C   2.22  3.0000
3  D   3.33  4.0000
4  E   0.00  5.0000
'''

Upvotes: 2

Related Questions