【问题标题】:How to change variable type when working with pandas-profiling?使用 pandas-profiling 时如何更改变量类型?
【发布时间】:2021-04-24 13:38:39
【问题描述】:

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

当使用 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()

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

【问题讨论】:

标签: python python-3.x pandas data-analysis pandas-profiling


【解决方案1】:

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

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

现在有了ProfileReport/profile_report中新添加的参数infer_dtypes,我们可以明确要求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)

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

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 2019-12-03
    • 2013-11-30
    相关资源
    最近更新 更多