Using python3.8, pandas 1.1.4
MRE:
df = pd.DataFrame({"a":[1,2,3,4,5, 6], "b":["01", "02", 1, "//N", None, np.nan]})
I want to convert column b to integer so that "01" = 1 (they should be same), "02"=2, etc... while replacing values that cannot be converted to integer to 0.
Current method:
c = []
for val in df["b"].unique():
try:
int(val)
except:
c.append(val)
pass
df["b"] = df["b"].replace(c, 0)
df["b"] = df["b"].astype(int)
outputting (it's desired output):
a b
0 1 1
1 2 2
2 3 1
3 4 0
4 5 0
5 6 0
Even though this works, I'm searching for more efficient and readable way.