Home > Blockchain >  How to replace specific values in columns only if it is the only one?
How to replace specific values in columns only if it is the only one?

Time:08-13

I have a dataframe:

id  val1                val2
1   "he bought 0"       "0"
2   "0"                 "0-the student"

i'd like to replace 0 with emptiness ("") but only in cases of "0". so for example "0-the student" shouldn't turn into "-the student". How could i do that? desired result is:

id  val1                val2
1   "he bought 0"       ""
2   ""                 "0-the student"

str.replace("0", "") will change "0-the student" and "he bought 0" too

CodePudding user response:

You could simply:

df[df == "0"] = ""

id        val1           val2
0  he bought 0               
1               0-the student

CodePudding user response:

What you have right now:

import pandas as pd
d = {'val1': ["he bought 0", "0"], 'val2': ["0", "0-the student"]}
df = pd.DataFrame(data=d)
print(df)

Cycling through each column, then each row. If element == "0", replace with ""

for c, col in enumerate(d):
    for r, row in enumerate(d[col]):
        if row == "0":
            d[col][r] = ""
df = pd.DataFrame(data=d)
print(df)
  • Related