gpt4 book ai didi

csv - Pandas to_csv : how to format floats in a column with mixed types

转载 作者:行者123 更新时间:2023-12-05 06:42:19 26 4
gpt4 key购买 nike

我有一个 df,其中包含一个包含浮点值和文本值的列。

df.some_column

0    48.5182
1 58.2259
2 some string
3 48.5182
4 17.4928

我想将所有值写入 CSV,并将 float 四舍五入为 0 位小数。因此,此列中的值将是:

48
58
some string
48
17

当我将其写入 CSV 时

df.to_csv(output_path,encoding='utf-8', index=False, float_format='%.0f')

float_format 被忽略,我得到十进制值。如果我先删除带有字符串的行,则会按预期使用 float_format。我四处寻找将值转换为 int 的方法,但没有找到在列上执行此操作的方法。

看起来我可以遍历所有值并将它们四舍五入,但我怀疑有一些更优雅的方法。

最佳答案

您可以将 dtype 转换为 str,然后在小数点处拆分并取整数部分:

In [70]:    
df['some_col'] = df['some_col'].astype(str)
df['some_col'] = df['some_col'].loc[df['some_col'].str.contains('.')].str.split('.').str[0]
df

Out[70]:
some_col
index
0 48
1 58
2 some string
3 48
4 17

然后当您调用 to_csv 时,您不需要 float_format 参数

关于csv - Pandas to_csv : how to format floats in a column with mixed types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37318122/

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