大 pandas :进行规范化时忽略字符串列 [英] Pandas: Ignore string columns while doing normalization

查看:93
本文介绍了大 pandas :进行规范化时忽略字符串列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码规范化熊猫数据框:

I am using the following code to normalize a pandas data frame:

df_norm = (df - df.mean()) / (df.max() - df.min())

当所有列均为数字时,此方法工作正常.但是,现在我在df中有一些字符串列,并且上述规范化得到了错误.有没有一种方法只能在数据帧的数字列上执行这种规范化(保持字符串列不变)?谢谢!

This works fine when all columns are numeric. However, now I have some string columns in df and the above normalization got errors. Is there a way to perform such normalization only on numeric columns of a data frame (keeping string column unchanged)? Thanks!

推荐答案

您可以使用select_dtypes计算所需列的值:

You can use select_dtypes to calculate value for the desired columns:

df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c'], 'c': [4, 5, 6]})

df

   a  b  c
0  1  a  4
1  2  b  5
2  3  c  6

df_num = df.select_dtypes(include=[np.number])

df_num

   a  c
0  1  4
1  2  5
2  3  6

然后您可以将它们分配回原始df:

And then you can assign them back to the original df:

df_norm = (df_num - df_num.mean()) / (df_num.max() - df_num.min())


df[df_norm.columns] = df_norm

df

     a  b    c
0 -0.5  a -0.5
1  0.0  b  0.0
2  0.5  c  0.5

这篇关于大 pandas :进行规范化时忽略字符串列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆