【问题标题】:How could I add the % to each value in the numpy array?如何将 % 添加到 numpy 数组中的每个值?
【发布时间】:2017-09-30 22:49:01
【问题描述】:

我有以下 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.        ]]

【问题讨论】:

标签: python pandas numpy


【解决方案1】:

由于您在评论中提到您想将其转换为数据框(我假设您的意思是 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 提供了大部分关键代码行。

【讨论】:

    【解决方案2】:

    如果您使用的是熊猫:

    (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
    

    【讨论】:

      【解决方案3】:

      如果需要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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-22
        • 2021-04-12
        • 2016-11-13
        • 1970-01-01
        • 2019-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多