【问题标题】:How to demean only numeric columns in a Pandas dataframe containing categorical variables?如何在包含分类变量的 Pandas 数据框中仅贬低数字列?
【发布时间】:2021-02-04 23:10:01
【问题描述】:

我有一个 Pandas 数据框,希望贬低每个数字列,保持分类变量列条目不变。通过"demean",我只想从每列条目中减去相应列中所有条目的平均值。

数据框来自Wisconsin Breast Cancer 目录中的 569 名患者,为每位患者列出了 10 个不同的数字测量值,以及 M(恶性)或 B(良性)的诊断。

import pandas as pd

df = pd.read_csv('data/UWbcd.csv')
%load_ext google.colab.data_table. #just for purposes of browsing the data
df - df.mean()

使用这种方法,每个数字列中的条目都被贬低了,但是分类变量,

df['Diagnosis']

全部变成NaN。

在贬低分类变量时,有没有一种有效的方法?

【问题讨论】:

  • df.apply(lambda s: s - s.mean() if (s.dtype == np.int or s.dtype == np.float) else s).

标签: python pandas


【解决方案1】:

我会做如下的事情,创建一个你想要去平均的列数组。

numerical_cols = ['col1', 'col2', 'col5']

您可以使用 loc 仅选择您想要的列,您可以将其分配给新的 df 或返回到当前数据框。

df.loc[:, numerical_cols] = df.loc[:, numerical_cols] - def.loc[:, numerical_cols].mean()

df_demean = df.loc[:, numerical_cols] - def.loc[:, numerical_cols].mean()

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 2014-02-25
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多