Reputation: 2158
I am trying replace number to '' blank if the row/column contains numbers. I tried the following it keeps complaing isdigit doesn't exist? I tried converting the column to string and doesn't help. Is there other operators that I could use for the pandas data frame?
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)
Looking for an output like this:
col1
0
1
2
3 ABC
4 3D
Upvotes: 2
Views: 11136
Reputation: 1121844
To access string methods on a series, you need to do so via the .str
attribute of Series
:
df1.col1.str.isdigit()
See Series.str.isdigit()
for the documentation.
You can use that as a boolean index and directly assign to the selected rows:
df1.col1[df1.col1.str.isdigit()] = ''
Do not use df1.col1.str.isdigit()
in an if
statement, because a boolean array is not True or False by itself, it is an array of boolean values and so would throw ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
if used in a boolean context.
Demo:
>>> 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
Upvotes: 5