Drive2blue
Drive2blue

Reputation: 127

Set dataframe row value to a numpy array value

Edited version of original post

I have a dataframe that's entirely populated with NaN. Specifically:

print(histPrice['Allocation %'])

[Output]: 
 Symbols    SPY  GLD  TLT   MA   QQQ      TIP
Date                                         
2019-11-01  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-31  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-30  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-29  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-28  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-25  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-24  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-23  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-22  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-21  NaN  NaN  NaN   NaN  NaN      NaN
2019-10-18  NaN  NaN  NaN   NaN  NaN      NaN

I have the following numpy array:

x = np.array([0.1,0.3,0.2,0.1,0.1,0.2])

I tried assigning the array to 2019-10-30 row by:

histPrice['Allocation %'].iloc[2] = x 

as well as

histPrice['Allocation %'].iloc[2,:] = x

Yet, both result in:

print(histPrice['Allocation %'].iloc[2])

[Output]: 
 Symbols
SPY       NaN
GLD       NaN
TLT       NaN
MA        NaN
QQQ       NaN
TIP       NaN
Name: 2019-10-30 00:00:00, dtype: float64 

I'm baffled as to why it's still outputting NaN. Any help would be greatly appreciated.

Upvotes: 1

Views: 3747

Answers (4)

U13-Forward
U13-Forward

Reputation: 71560

You need loc with indexing of df.index:

histPrice.loc[df.index[2], 'Allocation %'] = x 

Upvotes: 2

aprilangel
aprilangel

Reputation: 379

From the description, you are storing a dataframe in another single row dataframe.

And when doing below, You are setting an value in the copy of your dataframe.

histPrice['Allocation %'].iloc[2] = x 

Instead, try: (you can replace the 0 with your index)

histPrice.loc[0, 'Allocation %'].iloc[2] = x

Upvotes: 0

Rick
Rick

Reputation: 369

If you want to update the whole row with your numpy array, you should be able to use:

x = np.array([2,3,1])
df.iloc[2]= x

        Stock Bond Gold
2/01/19   NaN  NaN  NaN
1/31/19   NaN  NaN  NaN
1/30/19     2    3    1
1/29/19   NaN  NaN  NaN

This will update the row with each value of the array, and not just the first value.

I am curious if this will work for you?

import pandas as pd
import numpy as np
df = pd.DataFrame(columns=['Stock','Bond','Gold'], index=['2/01/19','1/31/19','1/30/19','1/29/19'])
histPrice = {}
histPrice['Allocation %'] = df
x = np.array([2,3,1])
histPrice['Allocation %'].iloc[2] = x 
print(histPrice['Allocation %'].iloc[2])

Upvotes: 0

BENY
BENY

Reputation: 323226

You should do

df.iloc[2,:]=a[0]
df
Out[142]: 
        Stock: Bond: Gold:
2/01/19    NaN   NaN   NaN
1/31/19    NaN   NaN   NaN
1/30/19    33%   33%   33%
1/29/19    NaN   NaN   NaN

Upvotes: 0

Related Questions