我有一个包含多个字符串值的 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/