【发布时间】:2021-12-29 15:24:55
【问题描述】:
我有一个 Pandas 数据框,它的 owner_type 列读取第一个、第二个、第三个等。我试图首先用数值 1、2、3 替换这些分类变量,然后在应用线性回归之前转换为浮点数数据框上的模型。当我使用替换来执行此操作时,我会返回所有空值。
我的最终目标:将 owner_type 的分类变量转换为数值。
我使用的代码。
cardata['Owner_Type'] = cardata['Owner_Type'].str.replace(r'[\xa0]',"")
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['First'], '1', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Second'], '2', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Third'], '3', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Fourth'], '4', inplace = True)
cardata['Owner_Type'] = cardata['Owner_Type'].replace(['Fourth & Above'], '5', inplace = True)
cardata['Owner_Type'].value_counts()
以上代码的输出是
Series([], Name: Owner_Type, dtype: int64
我对输出的期望:[1, 2, 3, 4, 5]
请帮忙。
【问题讨论】:
-
请提供允许我们重现相同输出的 DataFrame 示例。你应该阅读How to create a Minimal, Reproducible Example 和How to make good reproducible pandas examples。
标签: python pandas dataframe replace casting