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

How to change variable type when working with pandas-profiling?

重现问题,笔记本,数据,输出:github link
我的数据集中有 Contract variable/column,它看起来像这样,看起来都像数字,但它们实际上是分类的。

当用 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 类型。

很久没发这个问题了,raising issue and creating a pull request for this on pandas-profiling GitHub page, I almost forgot this question. I thank 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)

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