pandas 将我的列转换为 2 个小数位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42451387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting my column to 2 decimal places
提问by Omer Qureshi
I have a dataset:
我有一个数据集:
df = pd.read_excel('/Users/Adeel/Desktop/ECON628-01-omerqureshi84/datasets/main-data.xlsx')
It has columns with names such as "lerate" which is the log of the exchange rates for countries. It's in 5 decimal places and and I'm trying to convert it to 2 decimal places.
它具有名称为“lerate”的列,它是各国汇率的日志。它有 5 个小数位,我正在尝试将其转换为 2 个小数位。
I'm using the following code:
我正在使用以下代码:
for i in range(len(df.lerate)):
print ("%.2f" % df.lerate[i])
It's giving me an error.
它给了我一个错误。
Can anyone help? I don't know what's wrong here.
任何人都可以帮忙吗?我不知道这里出了什么问题。
回答by mechanical_meat
You can use round
:
您可以使用round
:
df.lerate = df.lerate.round(2)
Example:
例子:
>>> df = pd.DataFrame(np.random.random([3, 3]),
columns=['A', 'B', 'C'], index=['first', 'second', 'third'])
>>> df.A = df.A.round(2)
>>> df
A B C
first 0.82 0.581855 0.548373
second 0.21 0.536690 0.986906
third 0.78 0.100343 0.576521