JamesHudson81
JamesHudson81

Reputation: 2273

How could I add the % to each value in the numpy array?

I have the following numpy array:

arr= [[  0.          0.1046225518   0.          0.8953774482   0.        ]]

For the moment I have

values= str(np.around([arr*100],decimals=2))

returning:

 [[  0.          10.46   0.          89.53  0.        ]]

If I + % to values, it returns

 [[  0.          10.46   0.          89.53  0.        ]]%

The desired output is :

[[  0.          10.46%   0.          89.53%  0.        ]]

Upvotes: 1

Views: 1236

Answers (3)

jezrael
jezrael

Reputation: 862781

Also solution if need 0 only:

where + mul + round + astype

arr = np.array([[0.,0.1046225518,0., 0.8953774482, 0.]])

#DataFrame by constructor
df = pd.DataFrame(arr.reshape(-1, len(arr)), columns=['A'])

#convert 0 to string also for avoid mixed types - floats and strings 
df['B'] = df['A'].astype(str).where(df['A'] == 0, 
                                    df['A'].mul(100).round(2).astype(str).add('%'))
print (df)
          A       B
0  0.000000     0.0
1  0.104623  10.46%
2  0.000000     0.0
3  0.895377  89.54%
4  0.000000     0.0

Upvotes: 0

Luciano
Luciano

Reputation: 2418

If you are using pandas:

(pd.Series([  0.0, 0.1046225518, 0.0, 0.8953774482, 0.0]) * 10).round(2).astype(str) + " %"

Resulting in

0     0.0 %
1    1.05 %
2     0.0 %
3    8.95 %
4     0.0 %
dtype: object

Upvotes: 2

Max Power
Max Power

Reputation: 8954

Since you mentioned in a comment you'd like to convert this to a dataframe (I assume you mean a Pandas dataframe)...

import numpy as np
import pandas as pd

# Reproduce your numpy array
arr= np.array([[  0.0, 0.1046225518, 0.0, 0.8953774482, 0.0]])

# Convert to 1-Column DataFrame of % Strings 
# (use pd.Series() instead if you'd prefer this as a Pandas Series)
as_strings = pd.DataFrame(["{0:.2f}%".format(val * 100) for val in arr[0]])

# Assign column name
as_strings.columns = ['Numbers as Strings'] 

print(as_strings)

  Numbers as Strings
0              0.00%
1             10.46%
2              0.00%
3             89.54%
4              0.00%

thanks to this SO answer for most of the key line of code.

Upvotes: 3

Related Questions