为什么我无法在数据框熊猫中四舍五入

时间:2019-08-21 11:23:43

标签: python database pandas rounding

我正试图舍入到数据框中的一列。问题是我正在对数字进行排序,但是用小数点表示。

我尝试了不同的选择:

  • df['DataFrame column'].apply(np.ceil)

  • df['DataFrame column'].round(decimals=number of decimal places needed)

我的代码示例:

df = df.sort_values(by = ['SCORE'], ascending = False)

df['SCORE'].apply(np.ceil)

df

“ SCORE”列中的预期结果应为100.00000010096.1992059695.98335896

2 个答案:

答案 0 :(得分:0)

使用np.round()astype()

例如。

import pandas as pd
import numpy as np

df = pd.DataFrame({'SCORE':[100.000000,96.199205,np.nan,95.983358]})
print(df)
"""
   1. if series has NaN value, solution work for pandas 0.24+
      df['SCORE'] = np.round(df.SCORE).astype('Int64')
   https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html

  2. If series has not NaN value, try this
    df['SCORE'] = np.round(df.SCORE).astype(int)

"""
df['SCORE'] = np.round(df.SCORE).astype('Int64')
print(df)

O / P:

之前

        SCORE
0  100.000000
1   96.199205
2         NaN
3   95.983358

之后

     SCORE
0    100
1     96
2    NaN
3     96

答案 1 :(得分:0)

        FileSystemWatcher fsw = new FileSystemWatcher();
        string fullPath = "";
        DateTime tempTime;
        fsw.Path = @"C:\temp";

        private void startwatching()
        {
            timer1.Start();
        }
        fsw.EnableRaisingEvents = true;
        fsw.Created += Fsw_Created;

        private void Fsw_Created(object sender, FileSystemEventArgs e)
        {
            tempTime = DateTime.Now.AddSeconds(-4);
            fullPath = e.FullPath;
        }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (fullPath!=string.Empty)
        {
            timer1.Stop();
            if (tempTime >= Directory.GetLastAccessTime(fullPath))
            {
                DirectoryInfo di = new DirectoryInfo(fullPath);
                listBox1.Items.Add("Folder " + di.Name + " finished copying");
                fullPath = string.Empty;
            }
            else
            {
                tempTime = DateTime.Now;
            }
            timer1.Start();
        }
    }

如果您将数字传递给df["SCORE"] = df['SCORE'].round().astype(int) ,例如Series.round,它将为您提供带两位小数的序列。

  • round(2)以浮点数而不是整数给出结果
  • round()将浮点数转换为int