8

I have the following dataframe:

enter image description here

I'm trying to get rid of the percentage signs. In order to do this I decided to apply a function to the Democrat and Republican column and try to split() by the percentage sign. The following code tries to do that:

gallup_2012[['Democrat/Lean Democratic', 'Republican/Lean 
Republican']].apply(lambda x: x.split('%')[0])

However, when I try to do this, I get the following error:

("'Series' object has no attribute 'split'", u'occurred at index Democrat/Lean > Democratic')

I'm not quite sure why this error occurs, as I can apply other functions to this series. It's just that the split() function doesn't work.

Any help would be appreciated!

0

2 Answers 2

15

df[[ ]] returns a dataframe, so if you use df.apply() then it would be applied on pd.Series. And Series doesn't have split() method, But if you use df[ ] and use df.apply() then you would be able to achieve what you want. The drawback is only that you can apply only on one column.

gallup_2012['Democrat/Lean Democratic'].apply(lambda x: x.split('%')[0])
Sign up to request clarification or add additional context in comments.

2 Comments

How come when I do an operation like apply(lambda x: x+'s') this still works on every individual element even if I'm applying it to a dataframe?
see the output of df.apply(lambda x : type(x) and df['column'].apply(lambda x : type(x))
2

You could use the str.replace method on the desired columns

df["column"] = df["column"].str.replace("%", "")

2 Comments

Yeah I could, although I'm curious as to why the other method doesn't work
This doesn't work in pandas 0.25 AttributeError: Can only use .str accessor with string values!

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.