【问题标题】:Converting a column into floats except first few rows i.e selective conversion in a column将一列转换为浮点数,除了前几行,即一列中的选择性转换
【发布时间】:2026-01-06 00:30:01
【问题描述】:

我正在尝试进行一些数据处理,但每次都遇到相同的错误。 我的数据框(con_tc)如下所示:-

Index       u_p0       u_p1      u_p2.........u_p100
x            0          0          0            0
y            0          0          0            0
z            30         50         75          1000 
0.01        0.5        0.6       0.43          0.83
0.02        0.56       0.94      0.94          0.7
....
1000        0.4        0.5       0.45          0.56

当我运行这行代码时

con_tc.index = con_tc.index.map(lambda w: float(w) if (w not in 'xyz') else w)

试图将索引清理为浮点数,我收到错误

TypeError: 'in <string>' requires string as left operand, not float

这样做的目的是将除 x、y 和 z 之外的所有数值转换为浮点数。 基本情况

Index
  x
  y
  z
  0.01
  0.02
 ....
  1000

如果有人可以帮助我,那将是非常有帮助的。

【问题讨论】:

  • 您能解释一下为什么要将索引转换为浮点数吗?你不应该把它留给熊猫照顾吗?另外,您想将列中的数据转换为浮点数还是将列本身转换为浮点数?

标签: python dataframe openfoam


【解决方案1】:

也许你可以这样使用

con_tc[ 'float_u_p_0' ] = con_tc.apply( lambda x: float(x.u_p0) if x.Index  not in ("xyz") else x.u_p0

【讨论】: