我有以下numpy数组:
arr= [[ 0. 0.1046225518 0. 0.8953774482 0. ]]
目前我有
values= str(np.around([arr*100],decimals=2))
返回:
[[ 0. 10.46 0. 89.53 0. ]]
如果我+ %
为值,则返回
[[ 0. 10.46 0. 89.53 0. ]]%
所需的输出是:
[[ 0. 10.46% 0. 89.53% 0. ]]
答案 0 :(得分:3)
由于您在评论中提到过您想将其转换为数据框(我假设您的意思是Pandas数据框)...
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。
答案 1 :(得分: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
答案 2 :(得分:0)
如果仅需要0
,还可以解决方法:
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