2017-05-03 11 views
1

私は、次のnumpyの配列があります。I値へ+ %、それはnumpy配列の各値に%をどのように追加できますか?

[[  0.          10.46   0.          89.53  0.        ]]% 
を返す場合

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

を:私は戻って

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

を持っている現時点では

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

所望の出力は次のようになります。

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

あなたの出力は何ですか? numpyの配列の文字列、または単に文字列ですか? – Feodoran

+0

numpy文字列の配列の後にデータフレーム – ge00rge

+0

に関連しています:https://stackoverflow.com/questions/35661968/add-a-percent-sign-to-a-dataframe-column-in-python – EdChum

答えて

3

あなたは(私はあなたがパンダのデータフレームを意味すると仮定)のデータフレームにこれを変換したいコメントで述べたので...

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% 

感謝キーコードの大半はthis SO answerになります。

+0

グレートマックス、 ご協力いただきありがとうございます!! – ge00rge

1

あなたはパンダを使用している場合:

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

をまた

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

で解決策を結果として生じるのみ必要0場合:

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 
関連する問題