Python DatetimeIndex 错误 - TypeError: (“不能在 <class 'pandas.tseries.index.DatetimeIndex' 上做标签索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30676186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:26:34  来源:igfitidea点击:

Python DatetimeIndex Error - TypeError: ("cannot do label indexing on <class 'pandas.tseries.index.DatetimeIndex'

pythonpandas

提问by hb.klein

I have so far the following code provided by EdChum:

到目前为止,我有 EdChum 提供的以下代码:

In [1]:
df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]})
df["c"] =np.NaN

df["c"][0] = 1
df["c"][2] = 3


def func(x):
    if pd.notnull(x['c']):
        return x['c']
    else:
        return df.iloc[x.name - 1]['c'] * x['b']
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df

Out[1]:
      a   b    c
0  None   2    1
1  None   3    3
2  None  10    3
3  None   3    9
4  None   5   45
5  None   8  360

That also works perfectly well, but as soon as I change the index of the dateframe = df as follows:

这也很有效,但是只要我按如下方式更改 dateframe = df 的索引:

rng = pd.date_range('1/1/2011', periods=6, freq='D')

df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]},index=rng)

I get the following error: TypeError: ("cannot do label indexing on <class 'pandas.tseries.index.DatetimeIndex'> with these indexers [2011-01-01 00:00:00] of <class 'pandas.tslib.Timestamp'>", u'occurred at index 2011-01-02 00:00:00')

我收到以下错误: TypeError: ("cannot do label indexing on <class 'pandas.tseries.index.DatetimeIndex'> with these indexers [2011-01-01 00:00:00] of <class 'pandas.tslib.Timestamp'>", u'occurred at index 2011-01-02 00:00:00')

What is the problem here? How do I need to adjust the code in order to make it work with da DatetimeIndex?

这里有什么问题?我需要如何调整代码才能使其与 da DatetimeIndex 一起使用?

回答by EdChum

The following works, the difference here is that I get the integer location of the datetime value in the index using get_loc:

以下工作,这里的区别在于我使用以下方法获取索引中日期时间值的整数位置get_loc

In [48]:

rng = pd.date_range('1/1/2011', periods=6, freq='D')
df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3, 10, 3, 5, 8]},index=rng)
df["c"] =np.NaN
?
df["c"][0] = 1
df["c"][2] = 3
?
?
def func(x):
    if pd.notnull(x['c']):
        return x['c']
    else:
        return df.iloc[df.index.get_loc(x.name) - 1]['c'] * x['b']
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df['c'] = df.apply(func, axis =1)
df

Out[48]:
               a   b    c
2011-01-01  None   2    1
2011-01-02  None   3    3
2011-01-03  None  10    3
2011-01-04  None   3    9
2011-01-05  None   5   45
2011-01-06  None   8  360