【问题标题】:Getting all empty values after using Replace for specific column in Pandas Python在 Pandas Python 中对特定列使用替换后获取所有空值
【发布时间】: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]

请帮忙。

【问题讨论】:

标签: python pandas dataframe replace casting


【解决方案1】:

也许这会有所帮助。将您的值映射到浮动。任何未映射到 NaN 的更改。如果你真的想显示字符串,你可能需要使用 fillna(' ')。

df = pd.DataFrame({'Owner_Type':['\xa0', 'First', 'Second', 'Third', 'Fourth', 'Fourth & Above']})
df['Owner_Type'].map({'First': 1.0, 'Second': 2.0, 'Third': 3.0, 'Fourth': 4.0, 'Fourth & Above': 5.0}).value_counts()

1.0    1
2.0    1
3.0    1
4.0    1
5.0    1
Name: Owner_Type, dtype: int64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 2021-03-08
    • 1970-01-01
    • 2022-10-14
    • 2021-09-05
    • 2022-11-20
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多