gpt4 book ai didi

python - 如何在分组数据框上使用 fillna?

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:44 26 4
gpt4 key购买 nike

我想在多索引数据帧上使用 fillna,并仅在特定列位于同一索引中时填充该列。下一个索引可能以 n/a 开头,因此我无法在该列上调用 fillna 。组的大小正在变化,因此我无法通过数量来限制功能。

如果 df 是:

1                     Val
fooTitle barTitle
foo foo1 valueA
foo2 NaN
foo3 NaN
bar bar1 NaN
bar2 NaN
bar3 NaN
bar4 NaN
baz baz1 valueB
baz2 NaN
baz3 NaN

我希望它是:

1                     Val
fooTitle barTitle
foo foo1 valueA
foo2 valueA
foo3 valueA
bar bar1 NaN
bar2 NaN
bar3 NaN
bar4 NaN
baz baz1 valueB
baz2 valueB
baz3 valueB

我厌倦了使用 groupby(),但在指南中他们特别指出组对象是不可变的。 (他们特别提到 fillna:

Not perform in-place operations on the group chunk. Group chunks should be treated as immutable, and changes to a group chunk may produce unexpected results. For example, when using fillna, inplace must be False (grouped.transform(lambda x: x.fillna(inplace=False)))

)如何在每个组上使用该功能?

最佳答案

如果您要填充的值始终是问题中建议的第一个值,则以下方法有效。

df = df.groupby(level= "fooTitle").ffill()

关于python - 如何在分组数据框上使用 fillna?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55620039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com