【问题标题】:How to convert (number with % sign) to (round(number) with % sign)如何将(带 % 符号的数字)转换为(带 % 符号的圆形(数字))
【发布时间】:2018-11-22 18:51:09
【问题描述】:

df如下

    col1        col2
    10.56%      a
    55.78%      b
    700%        c
    118.13%     d
    200%        e
    102%        f
    45.25%      g
    67.765%     h

我想要 df['col1'] 如下所示(用 '%' 符号四舍五入到小数点 0):

col1
11%
56%
700%
118%
200%
102%
45%
68%

我的代码在某些条目上无法正常工作

df['col1'] = [re.sub("%","",str(x)) for x in list(df['col1'])]
df['col1'] = df['col1'].map(lambda x: pd.to_numeric(x, errors='ignore'))
df = df.round({'col1': 0})
df['col1'] = [re.sub(".0","%",str(x)) for x in list(df['col1'])]

比如 700% 变成 7%

118.13 到 %%

一些到 %6%

对于某些条目,它工作正常。

请帮帮我!!!

【问题讨论】:

  • 几乎每一行代码都违背了 pandas 的观点。去掉 % 后,df['col1'] = df['col1'].astype(int) 不会做你想要的吗?
  • @roganjosh 这给出了 ValueError: invalid literal for int() with base 10: '10.56'。同样对我来说,挑战是删除后再次添加 %
  • 是的,我发布了一个答案,在这样做的过程中,发现它并不像我最初想象的那么简单,因为您必须多次更改类型 :)

标签: python pandas dataframe rounding decimal-point


【解决方案1】:

快速而肮脏的方式:

import pandas as pd

perc_df = pd.DataFrame(
    {'col1' : ['65.94%', '761.19%', '17281.0191%', '9.4%', '14%'],
     'col2' : ['a', 'b', 'c', 'd', 'e']
})


perc_df['col1'] = pd.to_numeric(perc_df['col1'].str.replace('%', ''))
perc_df['col1'] = pd.Series([round(val, 2) for val in perc_df['col1']], index = perc_df.index)
perc_df['col1'] = pd.Series(["{0:.0f}%".format(val) for val in perc_df['col1']], index = perc_df.index)

【讨论】:

    【解决方案2】:

    你可以在strip'%'之后使用to_numeric

    pd.to_numeric(df.col1.str.strip('%')).round(0).astype(int).astype(str)+'%'
    0     11%
    1     56%
    2    700%
    3    118%
    4    200%
    5    102%
    6     45%
    7     68%
    Name: col1, dtype: object
    

    【讨论】:

      【解决方案3】:

      我会定义一个函数,这样我就可以用 apply() 循环它:

      def change(row, col):
          target = row[col]
          number = float(target.replace("%",""))
          number = round(number,0)
          return "{}%".format(int(number))
      
      df["col1"] = df.apply(change, col = "col1", axis = 1)
      

      【讨论】:

      • apply 未矢量化。它将以与在列表元素上调用函数相同的速度运行。
      • 你是对的@roganjosh,我将编辑我的答案以避免误导任何人。
      • 这种方法会比其他选项慢
      • @Chris 公平地说,它可能比this answer 更快,后者也抛出列表理解并多次调用Series 构造函数
      【解决方案4】:

      一种方式:

      import pandas as pd
      
      df = pd.DataFrame({'a': [1, 2, 3], 'b': ['10.2%', '5.3%', '79.6%']})
      
      df['b'] = df['b'].str.strip('%').astype(float).round(0).astype(int).astype(str) + '%'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-07
        • 1970-01-01
        • 2022-07-12
        • 2015-04-03
        • 1970-01-01
        • 2012-10-27
        • 1970-01-01
        相关资源
        最近更新 更多