熊猫数据框;将NaN转换为0时出错

时间:2017-05-17 18:13:17

标签: python pandas dataframe

我的数据帧的最后一步是将所有NaN值转换为0(零)。我的数据框包含1000多列,有些是文本,有些是整数,有些是浮点数。 要将NaN转换为0,我使用以下命令:

"","x"
"1",NA
"2",0.333333333333333
"3",0.333333333333333
"4",0.333333333333333
"5",1
"6",1
"7",1

这很好用,直到我添加了一个包含新数据的新列,这会产生以下错误:

#replace nan in columns with 0
nan_cols = df5c.columns[df5c.isnull().any(axis=0)]
for col in nan_cols:
    df5c[col] = df5c[col].fillna(0).astype(int)

这个错误意味着什么,我该如何解决?

我的数据框如下所示:

Traceback (most recent call last):
  File "pythonscript_v8.py", line 233, in <module>
    df5c[col] = df5c[col].fillna(0).astype(int)
  File "/usr/lib/python3/dist-packages/pandas/core/generic.py", line 2632, in astype
    dtype=dtype, copy=copy, raise_on_error=raise_on_error, **kwargs)
  File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line 2864, in astype
    return self.apply('astype', dtype=dtype, **kwargs)
  File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line 2823, in apply
    applied = getattr(b, f)(**kwargs)
  File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line 430, in astype
    values=values, **kwargs)
  File "/usr/lib/python3/dist-packages/pandas/core/internals.py", line 472, in _astype
    values = com._astype_nansafe(values.ravel(), dtype, copy=True)
  File "/usr/lib/python3/dist-packages/pandas/core/common.py", line 2463, in _astype_nansafe
    return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)
  File "pandas/lib.pyx", line 935, in pandas.lib.astype_intsafe (pandas/lib.c:16612)
  File "pandas/src/util.pxd", line 60, in util.set_value_at (pandas/lib.c:66830)
ValueError: invalid literal for int() with base 10: 'NODE_1_length_402490_cov_43.5825_ID_1'

1 个答案:

答案 0 :(得分:0)

如果我正确理解问题,这将有效。

                try {

        String Query = "INSERT INTO `stock`(`stock`, `min_stock`,   
                `id_stock`) VALUES ("

                + "\"" + p.get_Stock().getStock() + "\", "
                + "\"" + p.get_Stock().getStockMinimo() + "\","
                + "" + "null" + ")";

        Statement st = miConexion.createStatement();
        st.executeUpdate(Query);

        java.sql.ResultSet rs;
        rs = st.executeQuery("Select LAST_INSERT_ID() from stock limit 1");                
        rs.next(); //para posicionar el puntero en la primer fila
        ultimo_id = rs.getInt("LAST_INSERT_ID()");
        } catch (SqlException ex) { ex.printTrace;}