Alex
Alex

Reputation: 1131

label column values with currency, except cells which are string

i am looking for a solution to append a currency to floats. but my dataframe column also includes a string/empty cell. i expect a solution that only appends the currency to the floats in the column.

nr = [100, 200, 300, '' ,500]
text = ['a', 'b', 'c', 'd', 'e']

df = pd.DataFrame(list(zip(nr, text)),columns=['Nr', 'Text'])

i tried:


df['Nr'] = df['Nr'].astype(float).map("{:,.2f} €".format) #does not work

thanks for help.

Upvotes: 2

Views: 73

Answers (2)

Code Different
Code Different

Reputation: 93191

Try this:

df['Nr'] = pd.to_numeric(df['Nr']).map(lambda val: '' if np.isnan(val) else f'{val:,.2f} €')

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195553

You can use pd.to_numeric() with errors="coerce". This will convert all non-numeric values to NaN. Then use .notna() for boolean indexing:

m = pd.to_numeric(df.Nr, errors="coerce").notna()
df.loc[m, "Nr"] = df.loc[m, "Nr"].apply("{:,.2f} €".format)
print(df)

Prints:

         Nr Text
0  100.00 €    a
1  200.00 €    b
2  300.00 €    c
3              d
4  500.00 €    e

Upvotes: 1

Related Questions