微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 pandas-profiling 时如何更改变量类型?

如何解决使用 pandas-profiling 时如何更改变量类型?

为了重现问题、笔记本、数据、输出github link
我的数据集中有 Contract 变量/列,看起来像这样,看起来都像数字,但实际上是分类的。

enter image description here

当用 pandas 读取时,信息说它被读取为 int。由于合同变量是一个类别(来自我收到的元数据)所以我手动更改了变量类型,如下所示

df['Contract'] = df['Contract'].astype('categorical')
df.dtypes # shows modified dtype Now

然后我尝试从 pandas_profiling 获取报告。生成的报告显示 contact 被解释为实数,即使我将类型从 int 更改为 str/category

# Tried both,but resulted in same.
ProfileReport(df)
df.profile_report()

enter image description here

你能解释一下用 pandas_profiling 解释数据类型的正确方法吗?即,将 contract 变量更改为 categorical 类型。

解决方法

pandas-profiling GitHub 页面上发布此问题 raising issue 并为此创建了 pull request 很长时间后,我几乎忘记了这个问题。感谢 IampShadesDrifter 通过回答提醒我结束这个问题。

实际上,pandas-profiling 的这种行为是意料之中的。 pandas-profiling 尝试推断最适合列的数据类型。而且之前是这么写的。因为没有解决办法。它促使我在 GitHub 上创建了我的第一个 pull request

现在通过 infer_dtypes / ProfileReport 中新添加的参数 profile_report,我们可以明确要求 pandas-profiling 不推断任何数据类型,而是使用来自pandas (df.dtypes)。

# for the df in the question,df['Contract'] = df['Contract'].astype(str)

# by default it infers the dtype. So,`Contract` is read as number (because it looks like number).
ProfileReport(df) 
df.profile_report()

# `Contract` dtype now will be `str` as we explicitly type-casted with pandas.
ProfileReport(df,infer_dtypes=True) 
df.profile_report(infer_dtypes=True)

如果您发现任何值得一提的内容,请随时为本答案做出贡献。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。