Python AttributeError:"Series"对象没有属性"isdigit"



如果行/列包含数字,我正在尝试将数字替换为'''。我尝试了以下内容,它一直是不存在的iSdigit吗?我尝试将列转换为字符串,没有帮助。我还可以将其他操作员用于熊猫数据框架吗?

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

要在系列上访问字符串方法,您需要通过Series.str属性:

df1.col1.str.isdigit()

有关文档的参见Series.str.isdigit()

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

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

参见使用文本数据

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

最新更新