【问题标题】:removing numbers from a column in python pandas从 python pandas 的列中删除数字
【发布时间】:2018-11-13 19:21:51
【问题描述】:

我想删除 Python pandas 数据框中某个列的条目中的所有数字。不幸的是,像 .join().find() 这样的命令是不可迭代的(当我定义一个函数来迭代条目时,它给了我一条消息,即浮动变量没有 .find.join 属性)。在 pandas 中是否有任何命令可以解决这个问题?

def remove(data):

  for i in data if not i.isdigit():
    data=''         
    data=data.join(i)  
    return data

myfile['column_name']=myfile['column_name'].apply(remove()) 

【问题讨论】:

  • 提供一个前后 DataFrame 示例会很有帮助,这样我们就可以准确地确定您的意思和需要。
  • 我应该解释得更好,我想做的是将像 tin1t9in 这样的条目转换为 tintin,这意味着删除列中条目的数字字符。

标签: python string pandas


【解决方案1】:

您可以像这样删除所有数字:

import pandas as pd

df = pd.DataFrame ( {'x' : ['1','2','C','4']})
df[ df["x"].str.isdigit()  ] = "NaN"

【讨论】:

    【解决方案2】:

    如果没有数据样本就无法确定,但您的代码暗示 data 包含字符串,因为您在元素上调用了 isdigit

    假设上述情况,有很多方法可以做你想做的事。其中之一是条件列表理解:

    import pandas as pd
    s = pd.DataFrame({'x':['p','2','3','d','f','0']})
    out = [ x if x.isdigit() else '' for x in s['x'] ]
    # Output: ['', '2', '3', '', '', '0']
    

    【讨论】:

      【解决方案3】:

      或查看使用pd.to_numericerrors='coerce' 将列转换为数字并消除非数字值:

      使用@Raidex 设置:

      s = pd.DataFrame({'x':['p','2','3','d','f','0']})
      pd.to_numeric(s['x'], errors='coerce')
      

      输出:

      0    NaN
      1    2.0
      2    3.0
      3    NaN
      4    NaN
      5    0.0
      Name: x, dtype: float64
      

      编辑以处理任何一种情况。

      s['x'].where(~s['x'].str.isdigit())
      

      输出:

      0      p
      1    NaN
      2    NaN
      3      d
      4      f
      5    NaN
      Name: x, dtype: object
      

      s['x'].where(s['x'].str.isdigit())
      

      输出:

      0    NaN
      1      2
      2      3
      3    NaN
      4    NaN
      5      0
      Name: x, dtype: object
      

      【讨论】:

      • 但这不是删除数字吗?
      • @ChristianSloper 不,你会看到输出结果。
      • 所以你没有回答这个问题?
      • @ChristianSloper 好的。如果你这么说。我会让 OP 扩展他的要求。感谢您的意见。
      • 他说..如何删除数字,你展示如何删除非数字?我完全看不出你是如何回答这个问题的,但可以肯定。
      猜你喜欢
      • 1970-01-01
      • 2019-07-05
      • 2021-09-21
      • 2017-09-09
      • 2012-09-25
      • 2020-09-29
      • 2018-06-27
      • 2023-03-07
      • 2016-07-20
      相关资源
      最近更新 更多