Slartibartfast
Slartibartfast

Reputation: 1190

TypeError: cannot do positional indexing on DatetimeIndex with these indexers [stuff] of type str

I have sorted df:

d
    cost    margin
Date        
2018-12-28  -0.000351   0.006714
2021-04-27  -0.000618   0.011988
2021-07-06  -0.000806   0.006352
2021-02-02  -0.000825   0.017305
2018-11-28  -0.000831   0.004580
2021-05-18  -0.001560   0.004649
2019-04-15  -0.001607   0.003223
2019-02-21  -0.002103   0.006027
2019-08-09  -0.002264   0.008437

What i want to do is, to add row 1 and everything before it for both cost and margin and then row 2,1 and then row 3,2,1. So sum every row with everything before it till the end. To do this i have this :

for stuff in range(len(d)):
    for data in d.iloc[1:'stuff']:
        print(data)

But i am not even able to get the iterated data here and am getting this error:

TypeError: cannot do positional indexing on DatetimeIndex with these indexers [stuff] of type str

Could you please advise what i can do to resolve this.

Upvotes: 1

Views: 1127

Answers (1)

tlentali
tlentali

Reputation: 3455

Removing the quotes around stuff allows your code to run :

for stuff in range(len(d)):
    for data in d.iloc[1:stuff]:
        print(data)

However, we can reach your goal simply by using the cumsum() method on both columns cost and margin like so :

>>> d[['cost_sum', 'margin_sum']] = d[['cost', 'margin']].cumsum()
>>> d
    Date             cost     margin     cost_sum   margin_sum
0   2018-12-28  -0.000351   0.006714    -0.000351   0.006714
1   2021-04-27  -0.000618   0.011988    -0.000969   0.018702
2   2021-07-06  -0.000806   0.006352    -0.001775   0.025054
3   2021-02-02  -0.000825   0.017305    -0.002600   0.042359
4   2018-11-28  -0.000831   0.004580    -0.003431   0.046939
5   2021-05-18  -0.001560   0.004649    -0.004991   0.051588
6   2019-04-15  -0.001607   0.003223    -0.006598   0.054811
7   2019-02-21  -0.002103   0.006027    -0.008701   0.060838
8   2019-08-09  -0.002264   0.008437    -0.010965   0.069275

Upvotes: 1

Related Questions