Reputation: 47
I have a DF where some values have a prefix and I want to make a loop to remove it.
The DF looks like this:
I want to remove the "null-" and just leave the numbers.
I tried that, but I got and error message:
Upvotes: 1
Views: 538
Reputation: 9379
Like this:
df = df.applymap(lambda x: x if type(x) is not str or not x.startswith('null-') else x[len('null-'):])
Explanation:
applymap()
applies a function to every element in the DataFrame.UPDATE:
Here's a benchmarking comparison of my applymap()
based solution with a replace()
solution such as the one in the answer by @wwnde:
As the image above shows, replace()
is faster for very small dataframes (on the order of 100-1000 items), but for larger dataframes the applymap()
approach is the winner.
Upvotes: 2
Reputation: 26676
Use dataframe replace
df = df.replace(to_replace=r'null-', value='', regex=True)
Upvotes: 2
Reputation: 2372
df.apply(lambda x: x.str.replace("null-",""))
or, if you only want to remove from start:
df.apply(lambda x: x.str.lstrip("null-"))
Upvotes: 1