1

I have a pandas column with dtype 'object' that contains numeric values and the value '?'.

How should I proceed to count the number of rows that have the value '?' ?

I'm trying to run:

question_mark_count = df['column'].str.contains('\?').sum()

in a column that has numeric value and some question marks '?', but I'm getting the error:

AttributeError: Can only use .str accessor with string values!

When I run df.dtypes, I can see that the column is 'object' type.

I've also tried to convert the column to string:

df["column"] = df["column"].astype("string")

But I'm still getting the same error.

3
  • 1
    Should you not use .astype(‘int’) instead? Commented Oct 22, 2021 at 21:38
  • it won't work because I also have 0.0 values. It throws ValueError: invalid literal for int() with base 10: '0.0' Commented Oct 22, 2021 at 21:44
  • 1
    Did you try my example below? Commented Oct 22, 2021 at 21:46

3 Answers 3

1

to further explore possibilities:

df["column"].str.contains('\?').value_counts()

immune to np.nan pd.NA ints floats or whatever you have in your df['column']

Sign up to request clarification or add additional context in comments.

Comments

1

how about this?

>>> (df["column"].str.contains('\?')).astype('int').sum()

4 Comments

I got a ValueError: cannot convert float NaN to integer. Is is possible to concatenate a command to get rid of the NaN values as well in your proposed solution?
This is because you probably have NaN in ‘column’. Get rid of it first & then apply the solution above. It should work
df_concatenated['column'].isnull().any() returns false .
NaN != null. Also chec eliu’s solution with value_counts()
0

In my case the previous answer is almost correct. Try to add na=False in the call to the contains function:

df["column"].str.contains('\?', na=False).astype('int').sum()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.