python - 如何将 Pandas 数据框中的字符串值替换为整数?

标签 python pandas dataframe cosine-similarity

我有一个包含多个字符串值的 Pandas DataFrame。 我想用整数值替换它们以计算相似度。 例如:

stores[['CNPJ_Store_Code','region','total_facings']].head()
Out[24]: 
    CNPJ_Store_Code      region  total_facings
1    93209765046613   Geo RS/SC       1.471690
16   93209765046290   Geo RS/SC       1.385636
19   93209765044084  Geo PR/SPI       0.217054
21   93209765044831   Geo RS/SC       0.804633
23   93209765045218  Geo PR/SPI       0.708165

我想替换 region == 'Geo RS/SC' ==> 1, region == 'Geo PR/SPI'==> 2 等

Clarification: I want to do the replacement automatically, without creating a dictionary first, since I don't know in advance what my regions will be. Any ideas? I am trying to use DictVectorizer, with no success.

我确信有一种方法可以智能地做到这一点,但我就是找不到。

有人熟悉解决方案吗?

最佳答案

您可以使用 .apply() 函数和字典将所有已知的字符串值映射到它们对应的整数值:

region_dictionary = {'Geo RS/SC': 1, 'Geo PR/SPI' : 2, .... }
stores['region'] = stores['region'].apply(lambda x: region_dictionary[x])

关于python - 如何将 Pandas 数据框中的字符串值替换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31848877/

相关文章:

python - PyQt5 ListWidget 添加列表项

python - 使用 pytables 构造巨大的 numpy 数组

python - 如何将自定义字段添加到 Python 日志格式字符串?

python - 如何使用带逗号小数点分隔符的 pandas.to_clipboard

r - 模块 'rpy2.robjects.pandas2ri' 没有属性 'ri2py'

python - 为什么 "getcontext().prec = 2"没有实际设置它,以便 Decimal() 的使用达到两位小数?

python - Pandas 中 float() 的无效文字

python - 按 Pandas 中值的百分位数过滤列

python - Pandas如何将列按日期时间移动到不在索引中的日期时间

r - 如何按日期对数据框进行排序