Python DataFrame Replace values of specific conditions with nan

Asked 2 years ago, Updated 2 years ago, 69 views

I read the data from Panda through pd.read_csv.

pd = pd.read_csv('data.csv')
data= pd['header']

There's a zero in the read value has zero I want to give the value of 0 in nan. So,

data = data.replace(0,np.NAN)

If you give it, 0 changes to nan.

But I want to talk about no negative numbers I added conditions after reloading the data.

data= pd['header']
data = data.replace(0<data , np.NAN)

There is no error, but it does not change. That's all I'm saying

data[data<0] = 'nan'

If you do that, the nano value will be str.

Is there a way?

python pandas replace

2022-09-20 14:40

1 Answers

For DataFrame, all values not selected in the conditional statement are NaN processed. Therefore, if you want to replace a value less than 0 with a missing value in an existing DataFrame, the following code is sufficient.

data = data[data < 0]

For Series, list compression is available.

new_data = pd.Series([i if i < 0 else np.NaN for i in data])


2022-09-20 14:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.