Reputation: 2492
I have a pandas dataframe that looks like this:
Index Value
1 10
7 2
9 8
I am trying to input these values in an np.zeros
array that has a length of 10. The values in the dataframe should be in the numpy array corresponding to their index:
array([0.,10,0.,0.,0.,0.,0.,2,0.,8])
Whats the best way to do this? Thank you.
Upvotes: 3
Views: 979
Reputation: 51165
Using reindex
+ to_numpy
df['Value'].reindex(range(10), fill_value=0).to_numpy()
array([ 0, 10, 0, 0, 0, 0, 0, 2, 0, 8], dtype=int64)
Upvotes: 1
Reputation: 13397
Try:
df=pd.DataFrame({"Index": [1,7,9], "Value": [10,2,8]})
x=np.zeros(10)
x[df["Index"]]=df["Value"]
Outputs:
[ 0. 10. 0. 0. 0. 0. 0. 2. 0. 8.]
Upvotes: 2