【问题标题】:Remove the values ​after the decimal point in the dataframe - regex [duplicate]删除数据框中小数点后的值 - 正则表达式 [重复]
【发布时间】:2019-12-07 21:08:54
【问题描述】:

进入后:

df["column name"].unique()

该列具有这样的值:

array(['A','B','C','D','D,A,C','B,A'],
dtype=object)

我想把小数点后的值全部去掉,留下这样的东西:

array(['A','B','C','D','D','B'],
dtype=object)

即去掉小数点后的所有值,只留下第一个值。

我试试:

df["col name"] = df["col name"].astype(str).str.replace(r',\d+$', '')

但它对我不起作用。

【问题讨论】:

  • array(['A','B','C','D','D,A,C','B,A'], 有小数点还是小数点?这些字符串是由数字还是字母组成的?
  • 试试df['col name'] = df['col name].str.split(',').str[0]
  • @mrzasa 数字和字母

标签: python regex pandas dataframe


【解决方案1】:

您似乎有 字母 的 CSV 字符串,而不是数字,但无论如何,如果您只想删除(包括)第一个逗号之后的所有内容,那么也许只需尝试替换 @987654321 @ 带空字符串:

df["col name"] = df["col name"].astype(str).str.replace(r',.*$', '')

【讨论】:

    【解决方案2】:

    您可以将列表推导与split() 函数结合使用:

    df["col name"] = [ x.split(',')[0] for x in df["col name"] ] 
    

    【讨论】:

    • 如果你只对第一个值感兴趣,partitionsplit 更可取
    【解决方案3】:

    你可以使用extract

    df['col name'] = df['col name'].str.extract(r'([A-Z]*)')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 2018-07-16
      • 2016-10-15
      • 1970-01-01
      相关资源
      最近更新 更多