Pandas 使用 MultiIndex DataFrame 的 fillna 的 SettingWithCopyWarning

Pandas SettingWithCopyWarning for fillna with MultiIndex DataFrame

带有 fillna() 的行发出警告,即使它没有在原地执行。这是为什么?

import pandas as pd
import numpy as np


tuples = [('foo', 1), ('foo', 2), ('bar', 1), ('bar', 2)]
index = pd.MultiIndex.from_tuples(tuples)

df = pd.DataFrame(np.random.randn(2, 4), columns=index)
df.loc[0, ('foo', 1)] = np.nan

# this works without warning
# df = pd.DataFrame({'foo': [1, np.nan, 3], 'bar': [np.nan, 22, 33]]})  

df1 = df[['foo', 'bar']]
# df1 = df[['foo', 'bar']].copy()  # this does not help
filled = df1.fillna({'foo': 100, 'bar': 200}, inplace=False)

如果foobar是普通列,不是多索引的,就不会出现这个问题。

这是一个误报,不应在此处发出警告。我认为问题在于 fillna 不理解 "foo" 和 "bar" 适用于 MultiIndex 列的特定级别。

我建议在 GroupBy 中调用 fillna 作为解决方法,直到实现此功能。

fill = {'foo': 100, 'bar': 200}
df1.groupby(level=0, axis=1).apply(lambda x: x.fillna(fill[x.name]))

          foo                 bar          
            1         2         1         2
0  100.000000  1.040531 -1.516983 -0.866276
1   -0.055035 -0.107310  1.365467 -0.097696

或者,要直接使用 fillna,指定一个元组字典(因为,MultiIndex),

df1.fillna({('foo', 1): 100, ('foo', 2): 100})

          foo                 bar          
            1         2         1         2
0  100.000000  1.040531 -1.516983 -0.866276
1   -0.055035 -0.107310  1.365467 -0.097696