【发布时间】: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