2

wanted to replace values with "NaN" where percentage is greater than 100, in "ROE" column. Reading csv file. Following is the code, not sure how to assign values in 'missing' dataframe, please help

** ROE column in the dataset contains value like "25.00%", "130.00%", "50.00%". so while comparing, first need to convert values in the float by removing last character.

missing = pd.read_csv(local_path + "/Week4/Datasets_Week4/roemissing.csv")
print(missing)

for x in missing["ROE"]:
    y = float(x[:-1])
    if y>100:
        print(x.index)

2 Answers 2

1

Use the following:

missing['ROE'] = missing['ROE'].str[:-1].astype(int)
missing.loc[missing.ROE > 100, 'ROE'] = np.nan

missing.ROE > 100 will select the rows in which the ROE value is greater than 100. 'ROE' is the column name where you need to replace values of the selected rows.

All rows with ROE value greater than 100 are selected and then sets the value to NaN to the selected rows in the column ROE.

Sign up to request clarification or add additional context in comments.

3 Comments

In the dataset ROE column contains values like '28.00%', '120.00%' etc... not a float value. So '>' operator doesnt work. Need to first typecast to float by removing last character. Unable to do that
i tried below code "missing.loc[float(missing.ROE[:-1])>100, 'ROE'] = np.nan". it throws an error "cannot convert the series to <class 'float'>"
I recommend replacing the first line with missing['ROE'] = missing['ROE'].str.strip('%'), and using pd.to_numeric.
1

Use pd.Series.mask. The following will update the dataframe df in place.

df.update(df.ROE.mask(pd.to_numeric(df.ROE.str[:-1]) > 100))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.