熊猫数据框-将某些行或单元格的格式设置为2 d.p

时间:2020-01-21 09:32:30

标签: python pandas dataframe format

对于以下数据框,我想将前两行的格式重新设置为2个小数位。

       A         B    C        D     E   F
0     68        45        1843.4    98
1  978.1             23              3    
2                                  
3          49889.2   80              

我尝试过以下方法:

df.iloc[0:1,:].style.format("{0:.2f}")

对于其他项目,我还想格式化某些单元格,例如col B,索引3到49889.20(2 d.p.),是否会使用类似的方法?

感谢您的帮助

其他信息: 对于我正在做的事情,我正在创建一个混合的字符串/浮点数据框,以通过pylatex打印到LaTeX tex和PDF文档(请参见下面的PDF输出)。 pdf会打印实际的数据框,因此PDF会以与python输出相同的方式显示该数据框。 我想将值显示为2d.p。因为它们是财务数字。最好在数据框中而不是在pylatex过程中进行编辑。即因此pylatex仅打印数据框。在发布PDF之前,所有计算都已经完成,因此将值转换为字符串没有问题。谢谢。 enter image description here

3 个答案:

答案 0 :(得分:3)

将值更改为字符串,但是可以:

df.iloc[:2] = df.iloc[:2].applymap('{0:.2f}'.format)
print (df)
      A        B      C        D      E    F
0  0.00    68.00  45.00  1843.40  98.00  nan
1  1.00   978.10  23.00     3.00    nan  nan
2     2      NaN    NaN      NaN    NaN  NaN
3     3  49889.2     80      NaN    NaN  NaN

编辑:对于具有try-except的自定义功能,请使用:

def func(x):
    try:
        return '{0:.2f}'.format(x)
    except:
        return x

df = df.applymap(func)

答案 1 :(得分:1)

要以@jezrael的答案为基础,可以为各列传递字典:

String myvar = "TextTextText";

final Runtime rt = Runtime.getRuntime();
String[] commands = {"powershell.exe", "Set-Variable", "-Name \"myvar\" -Value \""+myvar+"\";", "echo $myvar"};

Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

String s = null;

while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

然后使用import pandas as pd import numpy import string #create some random data df = pd.DataFrame({k:v for k,v in zip(list(string.ascii_uppercase[:5]), np.random.random_sample((5,5)))}) A B C D E 0 0.995053 0.032561 0.556866 0.565944 0.613636 1 0.586174 0.932380 0.567946 0.277729 0.883482 2 0.210020 0.992571 0.626377 0.070947 0.723614 3 0.478476 0.866163 0.197633 0.621722 0.532891 4 0.743204 0.823418 0.616961 0.182829 0.642123 将产生:

df.style.format({'B': "{:.2f}", 'D': '{:+.2f}'})

出于完整性考虑:

       A         B          C         D        E
0   0.424395    0.23    0.960664    +0.96   0.992401
1   0.414769    0.57    0.664916    +0.73   0.850706
2   0.147415    0.88    0.873205    +0.12   0.33699
3   0.3742      0.28    0.496887    +0.74   0.885727
4   0.270247    0.67    0.501478    +0.10   0.113295

答案 2 :(得分:0)

格式化pandas DataFrame中的行很奇怪,因为类型是按列标准定义的,也许更改此(方向)可能会有所帮助。 可以在DataFrames上调用.Round()方法。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.round.html