pandas DataFrame DatetimeIndex slice error

I am very curious why I can assign value to a slice, but cannot print it out directly. Following codes shows details:

import pandas as pd
import numpy as np
from datetime import datetime

dt_start = datetime.strptime("20171010", "%Y%m%d")
dt_end = datetime.strptime("20171020", "%Y%m%d")

df = pd.DataFrame(np.nan, index=pd.date_range(start=dt_start, end=dt_end), columns=['sales', 'account'])

df.loc[:1, 'sales'] = 100 # works well
print(df.loc[:1, 'sales']) # error, why???

Error message:
TypeError: cannot do slice indexing on class 'pandas.tseries.index.DatetimeIndex with these indexers [1] of class 'int'

Why I can assign value but cannot print this slice?

Thanks very much for checking.

1 answer

  • answered 2017-10-11 10:24 jezrael

    I think first looks like bug:

    df.loc[:1, 'sales'] = 100 
    

    I think better is use iloc if need seelct by position - but need get_loc for position of column sales too:

    df.iloc[:1, df.columns.get_loc('sales')] = 100
    print (df)
                sales  account
    2017-10-10  100.0      NaN
    2017-10-11    NaN      NaN
    2017-10-12    NaN      NaN
    2017-10-13    NaN      NaN
    2017-10-14    NaN      NaN
    2017-10-15    NaN      NaN
    2017-10-16    NaN      NaN
    2017-10-17    NaN      NaN
    2017-10-18    NaN      NaN
    2017-10-19    NaN      NaN
    2017-10-20    NaN      NaN
    
    print (df.iloc[:1, df.columns.get_loc('sales')])
    2017-10-10   NaN
    Freq: D, Name: sales, dtype: float64
    
    print (df.columns.get_loc('sales'))
    0