Code challenge: Challenge (V) Complete the function fuzzy_values so it behaves as described in the docstring. Keep in mi
Posted: Sat Nov 27, 2021 2:28 pm
"""
import pandas as pd
import utils
def fuzzy_values(df):
""" Replaces the values in THE FIRST column of the
data frame `df` according to
the following criteria (IN THIS ORDER):
For each value in the FIRST column of `df` perform
the following
operations (in this order):
1. If the value is a number between 0 and 0.5 (so
0 <= value <= 0.5),
replace this value with the sum of the values of
all columns in this row.
2. If the value is between 1.0 and 2.0 (so 1.0
<= value <= 2.0), replace
this value with -99.
Important: The order matters! For instance, if in
part 1. the original
value is 0.1 and the sum of all columns (in that
row) is 1.5, this value
will be then replaced by -99 in part 2.
Parameters
----------
df : data frame
Any data frame including only
numeric data types (and no NaN). This
data frame must include at least two
columns.
You can assume that the `df` data
frame will meet the description
above. There is no need to check for
that. For instance, there is no
need to check that the `df` data
frame includes at least two columns,
or that it does not include any
NaN.
Returns
-------
data frame:
A data frame with values renamed
according to the criteria
above.
Columns: The same columns as
df.columns (in the same order)
Index: The same index as df.index
(in the same order)
Example
-------
If the data frame `df` is:
A
B
idx
0 0.4
1.0
1 0.0
0.5
2 10.0
0.0
3 1.5 -100.0
4 0.1
0.1
5 0.5 -10.0
This function will return the following data
frame:
A
B
idx
0 -99.0 1.0
1 0.5
0.5
2 10.0
0.0
3 -99.0 -100.0
4 0.2
0.1
5 -9.5 -10.0
"""
# <COMPLETE THIS PART>
#
----------------------------------------------------------------------------
# Please do not modify this function
#
----------------------------------------------------------------------------
def _mk_test_df():
""" Creates a testing data frame
A
B
idx
0 0.4
1.0
1 0.0
0.5
2 10.0
0.0
3 1.5 -100.0
4 0.1
0.1
5 0.5 -10.0
Notes
-----
For this example df, a valid output for
`fuzzy_values(df)` is
A
B
idx
0 -99.0 1.0
1 0.5
0.5
2 10.0
0.0
3 -99.0 -100.0
4 0.2
0.1
5 -9.5 -10.0
"""
cnts = """
idx , A , B
0 , 0.4 , 1
1 , 0 , 0.5
2 , 10 , 0
3 , 1.5 , -100
4 , 0.1 , 0.1
5 , 0.5 , -10
"""
fcsv = utils.fake_csv_file(cnts)
df = pd.read_csv(fcsv, index_col='idx')
return df
if __name__ == "__main__":
df = _mk_test_df()
utils.pprint(df, df_info=False)
res = fuzzy_values(df)
utils.pprint(res, df_info=False)
Code challenge: Challenge (V) Complete the function fuzzy_values so it behaves as described in the docstring. Keep in mind that your function should produce the correct output for any data frame that meets the conditions specified in the "Parameters" section of the doctring. Note: You do not have to check if the input data frame meets the conditions described in the "Parameters" section. Just assume that they do.