3

I have a strange problem which i am not able to figure out. I have a dataframe subset that looks like this

enter image description here

in the dataframe, I add "zero" columns using the following code:

subset['IRNotional]=pd.DataFrame(numpy.zeros(shape=(len(subset),1)))
subset['IPNotional]=pd.DataFrame(numpy.zeros(shape=(len(subset),1)))

and i get a result similar to this

enter image description here

Now when i do similar things to another dataframe i get zeros columns with a mix NaN and zeros rows as shown below. This is really strange.

subset['IRNotional]=pd.DataFrame(numpy.zeros(shape=(len(subset),1)))
    subset['IPNotional]=pd.DataFrame(numpy.zeros(shape=(len(subset),1)))

enter image description here

I dont understand why sometimes i get zeros the other i get either NaNs or a mix of NaNs and zeros. Please help if you can

Thanks

1
  • Do subset['IRNotional'] = 0 to assign a column of 0s. Commented Nov 14, 2018 at 15:34

1 Answer 1

8

I believe you need assign with dictionary for set new columns names:

subset = subset.assign(**dict.fromkeys(['IRNotional','IPNotional'], 0))
#you can define each column separately
#subset = subset.assign(**{'IRNotional': 0, 'IPNotional': 1})

Or simplier:

subset['IRNotional'] = 0
subset['IPNotional'] = 0

Now when i do similar things to another dataframe i get zeros columns with a mix NaN and zeros rows as shown below. This is really strange.

I think problem is different index values, so is necessary create same indices, else for not matched indices get NaNs:

subset['IPNotional']=pd.DataFrame(numpy.zeros(shape=(len(subset),1)), index=subset.index)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Jezrael. It was confusing the hell out of me. Just like you said i ll keep it simple and stick to the simplier version you suggested
@SBad - yes, I think I find problem, added to answer. You can test with your data

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.