【发布时间】:2020-06-23 08:12:15
【问题描述】:
这是我的多索引数据框:
A B C D E F G H I J
Chars Date
2020 January 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 February 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 March 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 April 4.0 66 45 26 99 20 13.5 15 3.8 3.2
Chars2 2020 January 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 February 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 March 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 April 4.0 66 45 26 99 20 13.5 15 3.8 3.2
例如,我想在 3 月和 3 月之后进行更改,但只更改“B”列。我该怎么做?
我试过了:
df.xs('Chars2')[df['B'].index.get_level_values(1).month >= 3] = 20.40
我收到了这个错误:
AttributeError: 'Index' object has no attribute 'month'
然后,我尝试了类似的方法。但我无法达到我想要的输出。
df.loc[pd.IndexSlice['B', pd.to_datetime(df.index.get_level_values(1), errors = 'coerce').month >= 3] = 20.40
我的预期输出:
A B C D E F G H I J
Chars Date
2020 January 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 February 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 March 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 April 4.0 66 45 26 99 20 13.5 15 3.8 3.2
Chars2 2020 January 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 February 4.0 66 45 26 99 20 13.5 15 3.8 3.2
2020 March 4.0 20.4 45 26 99 20 13.5 15 3.8 3.2
2020 April 4.0 20.4 45 26 99 20 13.5 15 3.8 3.2
【问题讨论】:
-
你能添加预期的输出DataFrame吗?
-
我添加了预期的输出 :)
标签: pandas indexing multi-index