【问题标题】:Python AttributeError: 'Series' object has no attribute 'isdigit'Python AttributeError:“系列”对象没有属性“isdigit”
【发布时间】:2019-03-11 19:16:31
【问题描述】:

如果行/列包含数字,我正在尝试将数字替换为“空白”。我尝试了以下它一直抱怨 isdigit 不存在?我尝试将列转换为字符串并没有帮助。我可以将其他运算符用于 pandas 数据框吗?

data = ['123567','1547892','2547879','ABC','3D']
df1 = pd.DataFrame(data)
df1.columns = ['col1']

df1.col1 = str(df1.col1)
if len(df1.col1) < 8 and df1.col1.isdigit(): # errors
    df1.col1 == ''
    print(df1)

寻找这样的输出:

col1
0   
1   
2   
3   ABC
4   3D

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    要访问系列中的字符串方法,您需要通过the .str attribute of Series

    df1.col1.str.isdigit()
    

    有关文档,请参阅 Series.str.isdigit()

    您可以将其用作布尔索引并直接分配给选定的行:

    df1.col1[df1.col1.str.isdigit()] = ''
    

    Working with Text Data

    不要在if 语句中使用df1.col1.str.isdigit(),因为布尔数组本身不是真或假,它是一个布尔值数组,因此如果在布尔上下文中使用会抛出ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

    演示:

    >>> import pandas as pd
    >>> data = ['123567','1547892','2547879','ABC','3D']
    >>> df1 = pd.DataFrame(data)
    >>> df1.columns = ['col1']
    >>> df1
          col1
    0   123567
    1  1547892
    2  2547879
    3      ABC
    4       3D
    >>> df1.col1[df1.col1.str.isdigit()] = ''
    >>> df1
      col1
    0
    1
    2
    3  ABC
    4   3D
    

    【讨论】:

    • 我之前尝试过,但是我得到了 ValueError: The truth value of a Series is ambiguous。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
    • @sharp:我已经在回答中向您展示了如何正确执行此操作。
    • 感谢它现在正在工作。不知道为什么它之前会导致该错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    • 2020-11-11
    • 2019-04-22
    • 2019-07-26
    • 2020-04-04
    • 2019-09-16
    相关资源
    最近更新 更多