Search code examples
pythonpandastype-conversionhextry-catch

Hex to decimal conversion with nan values


I am trying to convert a Pandas dataframe column data['hexValues'] consisting of hex values to decimal.

data["decValues"] = data.apply(lambda row: int(str(row["hexValues"]), 16), axis=1)

This works but the column hexValues look like this

0       FF
1        F
2      nan
3      nan
4     FFFF
5     FFFF
6        F
7        F
8        F
9        F
10      FF
11     nan
12     nan

I want to skip nan values, so if the value is nan, no conversion will take place. I thought of using try-except-else but I am not sure how I can do it. Can you help me?


Solution

  • If nans are missing values use:

    data["decValues"] = [int(x, 16) if pd.notna(x) else np.nan for x in data["hexValues"]]
    

    More general solution with try-except:

    def test(x):
        try:
            return int(x, 16)
        except ValueError:
            return np.nan
    
    data["decValues"] = data["hexValues"].apply(test)