2

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.

Dracrays
  • 147
  • 11

1 Answers1

2

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thank you, Jezrael. Your comment give me a spark, yes, maybe it is a bug. and I learned your solutions too, yes, that is great. I have another solution now, use ix. df.ix[:1, 'sales'] = 100, and we can print df.ix[:1, 'sales']. Because ix can use index, row/column seq and name mix. – Dracrays Oct 11 '17 at 11:06
  • 1
    Yes, `ix` help, but in last versions is [deprecated](http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated). – jezrael Oct 11 '17 at 11:07
  • Oh, that is a surprise. Then I would prefer your solution now. Do you know the reason why they deprecated it? – Dracrays Oct 11 '17 at 11:13
  • There is discussion about it [here](https://github.com/pandas-dev/pandas/issues/14218) – jezrael Oct 11 '17 at 11:15