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.

1
  • It looks like bug. Commented Oct 11, 2017 at 10:29

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Yes, ix help, but in last versions is deprecated.
Oh, that is a surprise. Then I would prefer your solution now. Do you know the reason why they deprecated it?
There is discussion about it here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.