【问题标题】:pandas groupby.agg() taking the mode of categorical variables where NaN is the only variable for a grouppandas groupby.agg() 采用分类变量的模式,其中 NaN 是组的唯一变量
【发布时间】:2021-07-11 22:51:36
【问题描述】:

我想为每个组找到最常见的值。 更新:如果有真实值和 NaN,我想删除 NaN。我只想要 NaN,这就是所有的值。

我的一些小组的所有数据都丢失了。我希望这些情况下的结果是缺失数据 (NaN) 作为最常见的值。

在这些情况下,DataFrame.groupby.agg(pd.Series.mode) 函数返回一个空分类。我想要的是 NaN。

下面是一个玩具示例...

data = """
Group, Value
A,      1
A,      1
A,      1
B,      2 
C,      3   
C, 
C, 
D,
D,
"""

from io import StringIO
df = (
    pd.read_csv(StringIO(data),
                skipinitialspace=True)
    .astype('category')
)

df.groupby('Group')['Value'].agg(pd.Series.mode)

产生...

A                                             1.0
B                                             2.0
C                                             3.0
D    [], Categories (3, float64): [1.0, 2.0, 3.0]
Name: Value, dtype: object

我的问题:有没有办法获得 NAN,或者检测空分类并将其设为 NaN。 已更新:请注意,我不能使用 dropna=False,因为这会给我上面 C 的错误答案。

作为上下文,我的原始 DataFrame 有 2700 万行,而我的分组框架有 600 万行。所以,我想避免缓慢的解决方案。

【问题讨论】:

  • 你试过df.replace('', 'NaN').groupby('Group')['Value'].agg(pd.Series.mode)吗?
  • 我有非 NaN 值我希望 NaN 被 mode 方法忽略。因此,在这种情况下,将 NaN 映射到其他东西不起作用。

标签: python pandas dataframe group-by


【解决方案1】:

您可以使用自定义聚合并检查isna().all():

df.groupby('Group')['Value'].agg(lambda x: x.mode() if not x.isna().all() else np.nan)

# Group
# A    1.0
# B    2.0
# C    3.0
# D    NaN
# Name: Value, dtype: float64

出于好奇,与df = pd.concat([df] * 100000) 计时(900,000 行):

>>> def coerce(df):
...    x = df.groupby("Group")["Value"].agg(pd.Series.mode)
...    return pd.to_numeric(x, errors="coerce")
>>> %timeit coerce(df)
22.1 ms ± 2.79 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
>>> def isna(df):
...    return df.groupby('Group')['Value'].agg(lambda x: x.mode() if not x.isna().all() else np.nan)
>>> %timeit isna(df)
20.9 ms ± 732 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

【讨论】:

  • 感谢基准测试,显然isna() 版本更快(对于更大的数据帧)。 +1
【解决方案2】:

您可以先申请pd.Series.mode,然后再申请pd.to_numeric 和errors="coerce":

x = df.groupby("Group")["Value"].agg(pd.Series.mode)
print(pd.to_numeric(x, errors="coerce"))

打印:

Group
A    1.0
B    2.0
C    3.0
D    NaN
Name: Value, dtype: float64

【讨论】:

    猜你喜欢
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    相关资源
    最近更新 更多