Answered step by step
Verified Expert Solution
Question
1 Approved Answer
4: Write a utility function to convert dollar values represented as strings (which do not sort correctly, e.g. '1B' sorts before '1k' and '10' sorts
4: Write a utility function to convert dollar values represented as strings (which do not sort correctly, e.g. '1B' sorts before '1k' and '10' sorts before '9') to dollar values represented as floats.
Write a function money_string_to_number(s) according to its docstring, below. You will need it, below, when processing DataFrame columns that contain money amounts like '3.4B' (3.4 billion dollars) and '7.8k' (7800 dollars).
In [ ]:
1
def money_string_to_number(s):
2
"""Returns float from money string s like '1.2T', '3.4B', '5.6M', or '7.8k'.
3
4
To handle nan as an input, it first converts s to str(s).
5
Then it makes these substitutions:
6
'T' -> 'e12' (trillion)
7
'B' -> 'e9' (billion)
8
'M' -> 'e6' (million)
9
'k' -> 'e3' (thousand)
10
Then it uses float() to convert the string to float.
11
"""
# ...
Here is some test code for the function:
inputs = ('1.2T', '3.4B', '5.6M', '7.8k')
outputs = [money_string_to_number(s) for s in inputs]
correct = [1.2e12, 3.4e9, 5.6e6, 7.8e3]
assert np.allclose(outputs, correct)
assert np.isnan(money_string_to_number(np.nan))
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started