eljusticiero67
eljusticiero67

Reputation: 2492

DataFrame with Index to Numpy Retaining Index

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

Answers (2)

user3483203
user3483203

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

Georgina Skibinski
Georgina Skibinski

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

Related Questions