4

I have an array:

([ 137.55021238,  125.30017675,  130.20181675,  109.47348838])

I need the array values to replace the b column, with the index number remaining the same:

Index    a         b         
0       0.671399 Nan
35      0.446172 Nan
63      0.614758 Nan
72      0.634448 Nan

I tried to use replace but it didn't work. Is there another way of doing this without turning array into a dataframe and merging?

3
  • df['b'] = [ 137.55021238, 125.30017675, 130.20181675, 109.47348838] why won't this work? Commented Oct 15, 2017 at 21:43
  • oh shoot. I overestimated the problem that had such a simple solution. Thank you @coldspeed. Should I erase this question that I posted? Commented Oct 15, 2017 at 21:47
  • I think this might be a duplicate, but it's okay to leave it be. Commented Oct 15, 2017 at 21:48

1 Answer 1

8
vals = [137.55021238, 125.30017675, 130.20181675, 109.47348838]

Option 1
Direct assignment.

df['b'] = vals
print(df)
              a           b
Index
0      0.671399  137.550212
35     0.446172  125.300177
63     0.614758  130.201817
72     0.634448  109.473488

Option 2
df.assign

df = df.assign(b=vals)
print(df)
              a           b
Index
0      0.671399  137.550212
35     0.446172  125.300177
63     0.614758  130.201817
72     0.634448  109.473488

Option 3
df.fillna

df.b = df.b.fillna(pd.Series(vals, index=df.index))
print(df)
              a           b
Index
0      0.671399  137.550212
35     0.446172  125.300177
63     0.614758  130.201817
72     0.634448  109.473488

If your values are Nan (string) instead of NaN (float), you can convert it, using df.replace:

df = df.replace('Nan', np.nan)
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. I'll accept your answer in 10 minutes @coldspeed
@piRSquared Thought of you when writing the assign :)

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.