SBad
SBad

Reputation: 1345

Adding a zero columns to a dataframe

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

Upvotes: 3

Views: 8215

Answers (1)

jezrael
jezrael

Reputation: 862511

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)

Upvotes: 8

Related Questions