Tony
Tony

Reputation: 1290

Format a pandas dataframe based on value type with unknown columns

I'm working on a website that takes excel sheets, converts it to a pandas dataframe, sending it back back with some calculations and formatting. So the user supplies the decimals and dataframes:

decimals = 2
df = pd.DataFrame([["a", 1], ["b", 2.2]], columns=["name", "value"])

And then some arbitrary trailing zeros/rouding position that the result needs to be sent back with:

name    value
a    1.00
b    2.20

I made it this far, until I started hitting type issues:

if decimals:
    pandas.options.display.float_format = f"{{:.{decimals}f}}".format
    df = df.astype(float)

but then of course df["name"] is going to be unable to convert:

ValueError: could not convert string to float: 'a'

If I knew ahead of it I could just use df.format() but in this situation they might upload arbitrary matrices comprised of strings, floats, or integers.

Upvotes: 1

Views: 317

Answers (1)

Nathan
Nathan

Reputation: 10326

Either check the current type, and convert only for types you want (any numeric type or only floats?) or you can convert everything that's convertible (easier to ask forgiveness than permission):

for col in df.columns:
    try:
        df[col] = df[col].astype(float)
    except ValueError:
        pass

Upvotes: 1

Related Questions