pandas 熊猫“时间戳”对象不可下标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49700253/
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-14 05:26:13  来源:igfitidea点击:

Pandas 'Timestamp' object is not subscriptable

pythonpandas

提问by Darkstarone

I have a Dataframe that I'm trying to run two different apply operations to:

我有一个 Dataframe,我正在尝试对其运行两个不同的应用操作:

last_consumption_of_year_index = df.loc[(df['date'].dt.month == 12) &
                                  (df['date'].dt.day == 31) &
                                  (df['date'].dt.hour == 23) &
                                  (df['date'].dt.minute == 30)].index[0]


df.loc[:last_consumption_of_year_index]['date'] = df.loc[:last_consumption_of_year_index]['date'].apply(lambda x: x['date'].replace(year=current_year-1))
df.loc[last_consumption_of_year_index+1:]['date'] = df.loc[last_consumption_of_year_index+1:]['date'].apply(lambda x: x['date'].replace(year=current_year))

What I want to do is replace the year of the timestamp with current_year-1for everything before last_consumption_of_year_index, and with current_yearfor everything after.

我想要做的就是替换时间戳的一年current_year-1一切之前last_consumption_of_year_index,用current_year了后的一切。

But I'm getting the error:

但我收到错误:

TypeError: 'Timestamp' object is not subscriptable

TypeError: 'Timestamp' object is not subscriptable

Inside in the lambdas. How should I be accessing the date objects?

在 lambdas 里面。我应该如何访问日期对象?

Additionally, if this isn't the best way to do this, could someone suggest a better way?

此外,如果这不是最好的方法,有人可以提出更好的方法吗?

回答by Ben.T

I believe one error might be in your lambda function and the presence of ['date'] in there. Try to replace lambda x: x['date'].replace(year=current_year-1)by lambda x: x.replace(year=current_year-1)as your method apply()is on a Serie and not a Dataframe.

我相信一个错误可能出在您的 lambda 函数中,并且其中存在 ['date']。尝试替换lambda x: x['date'].replace(year=current_year-1)by ,lambda x: x.replace(year=current_year-1)因为您的方法apply()是在 Serie 而不是 Dataframe 上。

Same with lambda x: x['date'].replace(year=current_year)by lambda x: x.replace(year=current_year)

lambda x: x['date'].replace(year=current_year)lambda x: x.replace(year=current_year)