为什么我的Python DataFrame类型转换自定义函数无法正常生效?
问题分析及修复方案
1. 日期列(Day)类型不符合预期的直接原因
你在把Day列转为datetime类型后,又调用了dt.strftime("%m/%d/%Y"),这个方法的作用是把 datetime 类型的值格式化为字符串,所以该列最终类型必然是object(pandas 中普通字符串序列的默认 dtype 就是 object)。
如果你的需求是保留 datetime 类型,删除df["Day"] = df["Day"].dt.strftime("%m/%d/%Y")这行即可。如果确实需要存储为指定格式的字符串,该列的 dtype 为 object 属于正常情况,你也可以指定使用 pandas 专用字符串类型:df["Day"] = df["Day"].dt.strftime("%m/%d/%Y").astype('string'),此时 dtype 会显示为string而非 object。
2. 字符串列(Channel、Partner)显示为object的原因
你使用astype(str)转换类型时,调用的是 Python 原生的 str 类型,对应在 pandas 中的 dtype 就是 object。如果需要显示为专用的字符串类型,改为astype('string')即可:
df[["Channel", "Partner"]] = df[["Channel", "Partner"]].astype('string')
3. 数值列(Spend等)显示为object的两个核心原因
- 首先你的
Platform Conversions列的空值替换逻辑写反了:where方法的规则是满足条件时保留原值,不满足条件时替换为后面的默认值,你当前的写法会把所有不等于"null"的值都替换为0,反而保留"null"字符串,后续转换 float 时因为存在字符串"null",要么报错要么强制转为 object 类型。正确的替换逻辑应该是:# 把等于"null"的替换为0,其他值保留 df['Platform Conversions'] = df['Platform Conversions'].where(df['Platform Conversions'] != "null", 0) # 更简洁的写法 # df['Platform Conversions'] = df['Platform Conversions'].replace("null", 0) - 其次如果函数调用时没有赋值返回结果,可能你修改的是函数内的副本,原 DataFrame 没有生效,调用函数时需要写:
df = dataType(df)
修复后的完整函数参考
import pandas as pd def dataType(df): '''This function makes sure the data type for all 7 columns of the final dataframe are correct''' # Day保留datetime类型,若需要字符串格式可自行调整 df["Day"] = pd.to_datetime(df["Day"]) # Channel, Partner转为pandas专用字符串类型 df[["Channel", "Partner"]] = df[["Channel", "Partner"]].astype('string') # 替换空值后转为float类型 df['Platform Conversions'] = df['Platform Conversions'].replace("null", 0) df[["Spend", "Clicks", "Impressions", "Platform Conversions"]] = df[["Spend", "Clicks", "Impressions", "Platform Conversions"]].astype(float) return df
内容的提问来源于stack exchange,提问作者Claie
相关产品推荐
相关产品推荐

