我有一个多索引 Dataframe ,有3个索引级别和2个数值列。
A 1 2017-04-01 14.0 87.346878
2017-06-01 4.0 87.347504
2 2014-08-01 1.0 123.110001
2015-01-01 4.0 209.612503
B 3 2014-07-01 1.0 68.540001
2014-12-01 1.0 64.370003
4 2015-01-01 3.0 75.000000
我想在新的第二级索引开始的地方替换第三级索引第一行中的值。例如:每第一行
(A,1,2017-04-01)->0.0 0.0
(A,2,2014-08-01)->0.0 0.0
(B,3,2014-07-01)->0.0 0.0
(B,4,2015-01-01)->0.0 0.0
Dataframe 太大了,像df.xs('A,1')...df.xs(A,2)
这样一帧一帧地做会很耗时。有什么方法可以让我得到一个掩码,然后在这些位置用新值替换吗?
4条答案
按热度按时间pxyaymoc1#
在
level=2
上使用DataFrame.reset_index
,然后在level=[0, 1]
上使用DataFrame.groupby
,并使用first
聚合level_2
,然后使用pd.MultiIndex.from_arrays
创建多级索引,最后使用此 * 多级索引 * 更改 Dataframe 中的值:结果:
svmlkihl2#
我们可以提取一系列的二级指标:
并使用以下命令检查它的变化:
因此,我们可以简单地使用
iloc
的第二条语句的返回值来获取每个二级索引的第一行,并修改它们的值,如下所示:输出:
ncecgwcz3#
可以在简单的
iloc
中使用grouperindices
:示例:
结果:
这比accepted answer快了大约7倍
zysjyyx44#
我想你可以这样写:
您可以从索引创建一个唯一值列表。然后获取索引位置,用行值替换列上的行值重合。
幸运的是,这可以帮助你。
干杯!