gpt4 book ai didi

python - Pandas iterrows 将整数更改为 float

转载 作者:太空狗 更新时间:2023-10-30 01:06:51 55 4
gpt4 key购买 nike

我正在尝试遍历包含一些 int64 和一些 float 的 DataFrame 的行。 iterrows() 似乎将我的整数转换为 float ,这破坏了我想在下游执行的所有操作:

>>> import pandas as pd
>>> df = pd.DataFrame([[10000000000000001, 1.5], [10000000000000002, 2.5]], columns=['id', 'prc'])
>>> [id for id in df.id]
[10000000000000001, 10000000000000002]
>>> [r['id'] for (idx,r) in df.iterrows()]
[10000000000000000.0, 10000000000000002.0]

直接遍历 df.id 没问题。但是通过 iterrows(),我得到了不同的值。有没有一种方法可以遍历行,这样我仍然可以按列名进行索引获得所有正确的值?

最佳答案

Here是文档的相关部分:

Because iterrows returns a Series for each row, it does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames) [...] To preserve dtypes while iterating over the rows, it is better to use itertuples() which returns namedtuples of the values and which is generally faster as iterrows.

您的数据示例:

>>> df = pd.DataFrame([[10000000000000001, 1.5], [10000000000000002, 2.5]], columns=['id', 'prc'])
>>> [t[1] for t in df.itertuples()]
[10000000000000001, 10000000000000002]

关于python - Pandas iterrows 将整数更改为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34749920/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com