【问题标题】:How to replace string values in pandas dataframe to integers?如何将熊猫数据框中的字符串值替换为整数?
【发布时间】:2015-10-29 04:41:21
【问题描述】:

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

澄清:我想自动进行替换,而无需先创建字典,因为我事先不知道我的区域将是什么。 有任何想法吗?我正在尝试使用 DictVectorizer,但没有成功。

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

任何熟悉解决方案的人?

【问题讨论】:

标签: python pandas dataframe cosine-similarity


【解决方案1】:

你可以这样做:

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)

【讨论】:

    【解决方案2】:

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

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

    我认为您只需将文本列的 dtype 更改为“类别”即可。

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-07
        • 2018-09-24
        • 2018-08-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 2017-07-08
        相关资源
        最近更新 更多