繁体   English   中英

如何将 dataframe 列中的数值更改为特定值?

[英]How to change numeric values in a dataframe column to specific values?

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

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

我曾尝试使用.replace function 但出现错误。

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

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

你可以做:

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 列只有有效数量的 boroughs(因此没有要忽略的值),您可以使用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM