pandas DataFrame DatetimeIndex切片错误

时间:2017-10-11 10:24:26

标签: python python-3.x pandas dataframe datetimeindex

我很好奇为什么我可以为切片赋值,但不能直接打印出来。以下代码显示详细信息:

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???

错误讯息:
TypeError:无法使用类' int'

的类索引器[1]对类' pandas.tseries.index.DatetimeIndex进行切片索引

为什么我可以分配值但无法打印此切片?

非常感谢您的检查。

1 个答案:

答案 0 :(得分:2)

我认为首先看起来像bug:

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

我认为更好的是使用iloc如果需要按位置选择 - 但需要get_loc来确定列sales的位置:

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