【问题标题】:Stop pandas from converting floating-point column indices to strings阻止 pandas 将浮点列索引转换为字符串
【发布时间】:2019-07-15 17:39:09
【问题描述】:

我正在使用pandas.read_csv 读取一个看起来像这样的 csv 文件(减去格式)

   , 0.1, 0.2
8  , 10,  20
8.1, 11,  22
8.2, 13,  25

我通过调用读取文件

pd.read_csv('file.csv', index_col=0)

生成的数据帧的列由'0.1''0.2'(即字符串)而不是0.10.2(即浮点数)索引。行索引转换为浮点数。

为什么不转换列索引?我怎样才能转换它们? (最好在我阅读文件时已经)。

【问题讨论】:

  • df.columns = df.columns.astype(float)df.columns = pd.to_numeric(df.columns, errors='ignore')?
  • @QuangHoang 谢谢,第一个有效(另一个我没试过)。
  • 没问题。请注意,如果您的列名称不是 float,则另一个会更好。

标签: python python-3.x pandas csv dataframe


【解决方案1】:

试试这个代码

dataframe.columns = pd.to_numeric(dataframe.columns, errors='ignore')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多