我有一个 DataFrame,其中的列中有许多缺失值,我希望对其进行分组:
import pandas as pd
import numpy as np
df = pd.DataFrame({'a': ['1', '2', '3'], 'b': ['4', np.NaN, '6']})
In [4]: df.groupby('b').groups
Out[4]: {'4': [0], '6': [2]}
看到 Pandas 删除了目标值为 NaN 的行。 (我想包括这些行!)
由于我需要许多这样的操作(许多列都有缺失值),并且使用比中位数更复杂的函数(通常是随机森林),所以我想避免编写过于复杂的代码。
有什么建议吗?我应该为此编写一个函数还是有一个简单的解决方案?
最佳答案
Pandas >= 1.1
从 pandas 1.1 开始,您可以更好地控制此行为,NA values are now allowed in the grouper使用dropna=False
:
pd.__version__
# '1.1.0.dev0+2004.g8d10bfb6f'
# Example from the docs
df
a b c
0 1 2.0 3
1 1 NaN 4
2 2 1.0 3
3 1 2.0 2
# without NA (the default)
df.groupby('b').sum()
a c
b
1.0 2 3
2.0 2 5
# with NA
df.groupby('b', <b>dropna=False</b>).sum()
a c
b
1.0 2 3
2.0 2 5
NaN 1 4
关于python - pandas GroupBy 具有 NaN(缺失)值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436594/