1

I wrote a function to eliminate spaces of a value in my dataframe.

def eliminate_space(words):
    return words.replace(' ', '')

Now I want to apply that function to each row in my 'words' column of my dataframe.

df['words']=df['words'].apply(eliminate_space(words))

It's saying the name 'words' is not defined. How do I adjust my code to be able to apply the function to each value in that column of my dataframe?

4
  • Can you explain it more? or else post full code Commented Dec 9, 2017 at 5:48
  • In my df table, I have multiple columns. One of them is called 'words'. For example, 'Hello there', 'Good bye'. I want to get rid of the spaces. I was asked to write a function to apply to each row of my df table to eliminate all spaces if there are any. Commented Dec 9, 2017 at 5:51
  • do you want it to apply only to words column or else all other columns too? Commented Dec 9, 2017 at 5:54
  • It could be to any column, but i was just specifying my columns 'words' here Commented Dec 9, 2017 at 5:58

1 Answer 1

2

You can use apply with lambda for that column of row:

df['words']=df['words'].apply(lambda row: eliminate_space(row))

Testing with example:

df = pd.DataFrame({'words':['word is 1', 'word is 2', 'word is 3']})
print(df)

Initial dataframe:

     words
0  word is 1
1  word is 2
2  word is 3

Using function:

df['words']=df['words'].apply(lambda row: eliminate_space(row))

Result:

     words
0  wordis1
1  wordis2
2  wordis3
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I forgot to think about iterating (using lambda) to each row
Great! Happy Coding .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.