对于以下将用作熊猫数据框的excel
df['% '] = (df['Code Lines'] / df['Code Lines'].sum())*100
输出自来
Language # of Files Blank Lines Comment Lines Code Lines %
C++ 15 66 35 354 3.064935065
C/C++ Header 1 3 7 4 0.034632035
Markdown 6 73 0 142 1.229437229
Python 110 1998 2086 4982 43.13419913
Tcl/Tk 1 14 18 273 2.363636364
YAML 1 0 6 20 0.173160173
Total 134 2154 2152 5775 50
我正在尝试让%列只能是2个带百分号的小数位
类似这样
Language # of Files Blank Lines Comment Lines Code Lines %
C++ 15 66 35 354 3.06%
C/C++ Header 1 3 7 4 0.03%
Markdown 6 73 0 142 1.22%
答案 0 :(得分:2)
使用round
,转换为字符串并添加%
:
df['%'] = ((df['Code Lines'] / df['Code Lines'].sum())*100).round(2).astype(str) + '%'