Home > Blockchain >  Loop to remove prefix in dataframe
Loop to remove prefix in dataframe

Time:07-07

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: enter image description here

I want to remove the "null-" and just leave the numbers. I tried that, but I got and error message: enter image description here

CodePudding user response:

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-"))

CodePudding user response:

Use dataframe replace

 df = df.replace(to_replace=r'null-', value='', regex=True)

CodePudding user response:

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.
  • The lambda above will work for heterogeneous data types (mix of numbers and strings, for example)
  • Related