'Add parentheses to column with NaN values
I have the following dataframe:
parameter parameter parameter
frc_var -0.01 0.01 0.01
beta NaN -0.01 -0.00
Illiquidity NaN 18.31 17.56
I want it to look like this:
parameter parameter parameter
frc_var (-0.01) (0.01) (0.01)
beta NaN (-0.01) (-0.00)
Illiquidity NaN (18.31) (17.56)
Solution 1:[1]
If need add strings () values use DataFrame.mask or DataFrame.where eith test missing or not missing values:
df = ('(' + df.astype(str) + ')').mask(df.isna())
print (df)
parameter parameter.1 parameter.2
frc_var (-0.01) (0.01) (0.01)
beta NaN (-0.01) (-0.0)
Illiquidity NaN (18.31) (17.56)
Or:
df = df.mask(df.notna(), ('(' + df.astype(str) + ')'))
For tuples is ouput different, solution is:
df = df.applymap(lambda x: (x, ) if pd.notna(x) else x)
print (df)
parameter parameter.1 parameter.2
frc_var (-0.01,) (0.01,) (0.01,)
beta NaN (-0.01,) (-0.0,)
Illiquidity NaN (18.31,) (17.56,)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
