【问题标题】:Pandas -- Replace dirty strings with intPandas - 用 int 替换脏字符串
【发布时间】:2018-08-16 02:27:21
【问题描述】:

我正在尝试做一些机器学习练习,但我的数据框的 ID 列给我带来了麻烦。我有这个:

0    LP001002
1    LP001003
2    LP001005
3    LP001006
4    LP001008

我想要这个:

0    001002
1    001003
2    001005
3    001006
4    001008

我的想法是使用replace 函数ID.replace('[LP]', '', inplace=True),但这实际上并没有改变系列。有人知道转换此列的好方法吗?

【问题讨论】:

  • 改成'LP'?
  • 我尝试的第一件事;它没有效果。

标签: python regex pandas replace


【解决方案1】:

你可以使用replace

df
Out[656]: 
        Val
0  LP001002
1  LP001003
2  LP001005
3  LP001006
4  LP001008
df.Val.replace({'LP':''},regex=True)
Out[657]: 
0    001002
1    001003
2    001005
3    001006
4    001008
Name: Val, dtype: object

【讨论】:

    【解决方案2】:

    以下内容适用于给出的示例:

    import pandas as pd
    df = pd.DataFrame({'colname': ['LP001002', 'LP001003']})
    
    # Slice off the 0th and 1st character of the string
    df['colname'] = [x[2:] for x in df['colname']]
    

    如果这是您的索引,您可以通过df['my_index'] = df.index 访问它,然后按照其余说明进行操作。

    一般来说,您可以考虑使用类似 scikit learn 中的 label encoder 之类的东西来将非数字元素转换为数字元素。

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2017-01-28
      • 2022-01-03
      • 2016-11-28
      • 1970-01-01
      相关资源
      最近更新 更多