如何将(带 % 符号的数字)转换为(带 % 符号的圆(数字))

How to convert (number with % sign) to (round(number) with % sign)

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%

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

请帮我解决这个问题!!!

您可以在 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

一种方式:

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) + '%'

快速而肮脏的方式:

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)

我会定义一个函数,这样我就可以用 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)