0

so i am kind of stuck here, my data is something like this

df = pd.DataFrame({'X': [1, 2, 3, 4, 5, 4, 3, 2, 1],
                   'Y': [6, 7, 8, 9, 10, 9, 8, 7, 6],
                   'Z': [11, 12, 13, 14, 15, 14, 13, 12, 11]})

id like to write a code to set the values of the rows 6 to 9 of the column 'Z' to NaN.

the best ive come to do is:

df.replace({'Z': { 6: np.NaN, 7: np.NaN }})

but all this does is replaces values for the new value if set in column Y.

i am confused as to how to change the values of the rows in a column if some values are same in that particular column.

3 Answers 3

1

You can use the loc indexer for your dataframe. I've used column 6 to 8 because df doesn't have a column 9:

df.loc[range(6, 9), 'Z'] = pd.NA
1

you could use:

df.Z[6:9] = np.NaN
1

I think you should use .iloc for this.

First of all, the index is zero based, so there is no row 9.

To change the values from row 5 to 8 on column 'Z' to pd.NA you could do something like this:

df.iloc[6:9,2:] = pd.NA

I'm assuming Pandas > 1.0 which introduced NA values.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.