【问题标题】:pandas float64 DataFrame column not behaving like one (wrt describe and to_csv functions)pandas float64 DataFrame 列的行为不像一个(wrt describe 和 to_csv 函数)
【发布时间】:2017-08-20 01:29:42
【问题描述】:

我正在尝试将来自 read_excel 和一些操作的 pandas (v0.19.2) DataFrame 导出到 CSV 文件。

虽然有些列被识别为 float64,但在 to_csv 函数中的 describe 方法和 float 格式都不起作用...(尽管它们可以完美地处理随机生成的数据)。

基本上就是一行

df["my_column"].describe()

返回这个:

count     5.0
unique    5.0
top       7.0
freq      1.0
Name: my_column, dtype: float64

虽然我希望它返回这样的东西

count    6.000000
mean     0.276880
std      1.032943
min     -1.542513
25%     -0.103334
50%      0.797131
75%      0.896404
max      1.083524
Name: my_column, dtype: float64

导出到 CSV 文件也是如此:

df["my_column"].to_csv("test.csv", sep=';', decimal=',', float_format="%.2f")

创建以下文件:

0;220
1;154
2;7
3;140.800003051758
4;48.4000015258789

虽然我期望:

0;220,00
1;154,00
2;7,00
3;140,80
4;48,40

我错过了什么吗?

【问题讨论】:

  • 可能需要先转换为float - df["my_column"].astype(float).to_csv("test.csv", sep=';', decimal=',', float_format="%.2f")
  • 太棒了!它有效(也适用于.describe())!我真的不明白为什么,因为 pandas 已经告诉我这是一个float,但是谢谢!

标签: python csv pandas


【解决方案1】:

您需要先由astype 转换为float,因为似乎有些值是字符串和一些数字:

df["my_column"].astype(float).to_csv("test.csv", sep=';', decimal=',', float_format="%.2f")

【讨论】:

  • 太棒了!它有效(也适用于.describe())!我真的不明白为什么,因为 pandas 已经告诉我这是一个float,但是谢谢!
猜你喜欢
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 1970-01-01
  • 2012-10-04
  • 2021-07-24
  • 2014-02-20
相关资源
最近更新 更多