如何将pandas dataframe中的字符串值替换为整数?

2024-10-01 13:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含几个字符串值的Pandas数据帧。 为了计算相似度,我想用整数值替换它们。 例如:

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.

我肯定有一种聪明的方法可以做到,但我就是找不到。在

有人知道解决方案吗?在


Tags: tostore字符串gtspipandascodepr
3条回答

在我看来你真的很喜欢熊猫类

http://pandas-docs.github.io/pandas-docs-travis/categorical.html

我想您只需要将文本列的数据类型改为“category”就可以了。在

stores['region'] = stores["region"].astype('category')

您可以:

df = pd.read_csv(filename, index_col = 0)  # Assuming it's a csv file.

def region_to_numeric(a):
    if a == 'Geo RS/SC':
        return 1
    if a == 'Geo PR/SPI':
        return 2


df['region_num'] = df['region'].apply(region_to_numeric)

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

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

相关问题 更多 >