M Smith
M Smith

Reputation: 430

Return zeros where index is out of range using pandas

I am currently working with a Pandas dataframe which contains 721 rows, from which I wish to select subsets of length n.

However, if the chosen subset exceeds the upper bound, I need to return zeros where the index is out of range. For example, I need MyDataframe['Column X'][719:725] to return [0.998, 0.965, 0, 0, 0, 0] (where 0.998 and 0.965 are the 720th and 721st values of my dataframe respectively).

Does pandas natively allow you to do this?

Upvotes: 2

Views: 136

Answers (1)

jezrael
jezrael

Reputation: 863196

If there is default index you can add new rows filled by 0 with DataFrame.reindex before selecting:

MyDataframe = MyDataframe.reindex(range(726), fill_value=0)

Upvotes: 1

Related Questions