【问题标题】:How to change numeric values in a dataframe column to specific values?如何将数据框列中的数值更改为特定值?
【发布时间】:2022-01-05 23:43:40
【问题描述】:

我正在尝试将数据框中列的一组数字标识符值转换为字符串值。

new_housing.replace({'borough': {'1':'Manhattan', '2':'Bronx', '3':'Brooklyn', '4':'Queens', '5':'Staten Island'}})

我曾尝试使用 .replace 函数,但遇到了错误。

TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'

我对 Python 编码相当陌生,这似乎是与列中的数据类型相关的问题。任何帮助,将不胜感激。谢谢

【问题讨论】:

标签: python pandas dataframe replace


【解决方案1】:

你可以这样做:

boroughs_dict = {'1':'Manhattan', '2':'Bronx', '3':'Brooklyn', '4':'Queens', '5':'Staten Island'}
new_housing.borough = new_housing.boroughs.map(lambda x: boroughs_dict.get(str(x),x))

这将找到转换为 str 的 borough 数并忽略未找到的值。 如果您知道 borough 列有 only 有效的行政区数(因此没有值可以忽略),您可以使用:

new_housing.borough = new_housing.boroughs.astype(str).map(boroughs_dict)

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 2020-10-18
    • 2020-07-19
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2019-10-06
    • 2017-12-15
    • 1970-01-01
    相关资源
    最近更新 更多