0

I have a dataset in which few values are null. I want to change them to either 4 or 5 randomly in specific rows. How do I do that?

data.replace(np.nan, np.random.randint(4,5))

I tried this and every nan value changed to only 4 and not 4 and 5 randomly. Also I dont know how to replace nan values for only specific rows like row 1,4,5,8.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
sg-23
  • 1
  • data = data.replace('?', np.nan) has done the job for me – Ged0jzn4 Nov 09 '22 at 17:51
  • It'd help to provide some example input data and your desired output, as well as the output you're currently getting for completeness. See [How to make good reproducible pandas examples](/q/20109391/4518341). BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want more tips. See also [mre] in general. – wjandrea Nov 09 '22 at 17:55
  • BTW, I edited your question to fix the formatting. See [code formatting help](/editing-help#code). – wjandrea Nov 09 '22 at 17:55
  • You'll only ever get 4 out of this cause `np.random.randint`'s `high` parameter is exclusive – wjandrea Nov 09 '22 at 18:21
  • After thinking about it, this seems to be at least two questions in one. For the "specific rows" part, what research have you done or what have you tried? Like, do you at least know how to [select certain rows by index](/q/19155718/4518341)? – wjandrea Nov 09 '22 at 18:29

1 Answers1

0

Use loc and select by index and isna. Change np.random.randint(4,5) to (4,6) to get both four and fives.

import pandas as pd
import numpy as np

data = {
    'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'B': [0, np.nan, 1, 2.0, 2, np.nan, 3, 2.0, 7, np.nan]}
df = pd.DataFrame(data)
#  A   B
#  1 0.0
#  2 NaN
#  3 1.0
#  4 2.0
#  5 2.0
#  6 NaN
#  7 3.0
#  8 2.0
#  9 7.0
# 10 NaN

# If index is 1 or 5, and the value is NaN, change B to 4 or 5
df.loc[df.index.isin([1, 5]) & pd.isna(df["B"]), "B"] = np.random.randint(4,6)
#  A   B
#  1 0.0
#  2 4.0
#  3 1.0
#  4 2.0
#  5 2.0
#  6 4.0
#  7 3.0
#  8 2.0
#  9 7.0
# 10 NaN
wjandrea
  • 28,235
  • 9
  • 60
  • 81
BERA
  • 1,345
  • 3
  • 16
  • 36