I have a dataframe and an array. The array has two values and I would like to insert the values from the array in the dataframe. I want to insert the array values on index '2020-12-31' and columns 'v2' and 'v3' (so I want to replace 300 with 305 and 250 with 255).
import pandas as pd
import numpy as np
df=pd.DataFrame({'v0': [3,4,5,6,7,8,9,10,11,12,13,14],
'v1': [600, 550, 600, 600, 600, 600, 550, 500, 450, 350, np.NaN, np.NaN],
'v2': [350, 400, 450, 500, 450, 400, 450, 400, 350, 300, np.NaN, np.NaN],
'v3': [350, 350, 450, 500, 450, 400, 400, 300, 300, 250, np.NaN, np.NaN]},
index=pd.date_range('2020-03-31', '2021-02-28', freq='M'))
array=np.array([305, 255])
CodePudding user response:
Use DataFrame.loc
with list of columns names, it working because same length like array:
df.loc['2020-12-31', ['v2','v3']] = array
print (df)
v0 v1 v2 v3
2020-03-31 3 600.0 350.0 350.0
2020-04-30 4 550.0 400.0 350.0
2020-05-31 5 600.0 450.0 450.0
2020-06-30 6 600.0 500.0 500.0
2020-07-31 7 600.0 450.0 450.0
2020-08-31 8 600.0 400.0 400.0
2020-09-30 9 550.0 450.0 400.0
2020-10-31 10 500.0 400.0 300.0
2020-11-30 11 450.0 350.0 300.0
2020-12-31 12 350.0 305.0 255.0
2021-01-31 13 NaN NaN NaN
2021-02-28 14 NaN NaN NaN