简体   繁体   中英

Replace pandas column values with array

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM