gpt4 book ai didi

python - 使用 MultiIndex DataFrame 进行 fillna 的 Pandas SettingWithCopyWarning

转载 作者:太空宇宙 更新时间:2023-11-03 20:48:58 28 4
gpt4 key购买 nike

带有 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

关于python - 使用 MultiIndex DataFrame 进行 fillna 的 Pandas SettingWithCopyWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394686/

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