简体   繁体   English

pandas 将系列转换为 int 时四舍五入

[英]pandas rounding when converting the series to int

How can I round a number of decimals based on an assigned series?如何根据分配的系列舍入多个小数? My sample data is like this:我的样本数据是这样的:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.uniform(1,5,size=(10,1)), columns=['Results'])
df['groups'] = ['A', 'B', 'C', 'D']
df['decimal'] = [1, 0, 2, 3]

This produces a dataframe like:这会产生一个 dataframe,例如:

   Results    groups  decimal  
0  2.851325      A        1
1  1.397018      B        0
2  3.522660      C        2
3  1.995171      D        3

Next: each result number needs to be rounded the number of decimals shown in decimal .接下来:每个结果数字需要四舍五入到 decimal 所示的decimal What I tried below resulted in an error of TypeError: cannot convert the series to <class 'int'>我在下面尝试的结果导致错误TypeError: cannot convert the series to <class 'int'>

df['new'] = df['Results'].round(df['decimal'])

I want the results like:我想要这样的结果:

   Results     groups decimal new
0  2.851325      A        1   2.9
1  1.397018      B        0   1
2  3.522660      C        2   3.52
3  1.995171      D        3   1.995

You can pass a dict-like object to DataFrame.round to set different precision levels for different columns.您可以将类似 dict 的 object 传递给DataFrame.round来为不同的列设置不同的精度级别。 So you need to transpose a single column DataFrame (constructed from Results column) twice:因此,您需要将单列 DataFrame(从Results列构建)转置两次:

df['Results'] = df[['Results']].T.round(df['decimal']).T

Another option is a list comprehension:另一种选择是列表理解:

df['Results'] = [round(num, rnd) for num, rnd in zip(df['Results'], df['decimal'])]

Output: Output:

   Results groups  decimal
0    2.500      A        1
1    2.000      B        0
2    2.190      C        2
3    1.243      D        3

Note that since it's a single column, it's decimal places is determined by the highest decimal;请注意,由于它是单列,因此它的小数位由最高小数位决定; but if you look at the constructor of this DataFrame, you'll see that the precisions have indeed changed:但是如果你看一下这个 DataFrame 的构造函数,你会发现精度确实发生了变化:

>>> df[['Results']].to_dict('list')
{'Results': [2.5, 2.0, 2.19, 1.243]}

Try this:尝试这个:

df['new']=df['Results'].copy()
df=df.round({'new': 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM