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%
对于某些条目,它工作正常。
请帮助我!!!
答案 0 :(得分:1)
您可以在{%{%}}之后使用to_numeric
strip
答案 1 :(得分: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 :(得分:0)
一种方法:
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) + '%'
答案 3 :(得分:0)
我将定义一个函数,以便可以使用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)