作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想用 df
中的 A
替换 B
中的 nan
值:
df:
A B
0 Bb00 100080
1 Aa00 <NA>
2 Cc10 450089
df 数据类型:
A object
B Int64
dtype: object
我试过:
df['new_col'] = df['B'].fillna(df['A'])
它发现错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-120-1d24cd9977ed> in <module>
2 print(df.dtypes)
3
----> 4 df['new_col'] = df['B'].fillna(df['A'])
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\series.py in fillna(self, value, method, axis, inplace, limit, downcast)
4515 downcast=None,
4516 ) -> Optional["Series"]:
-> 4517 return super().fillna(
4518 value=value,
4519 method=method,
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\generic.py in fillna(self, value, method, axis, inplace, limit, downcast)
6046 )
6047
-> 6048 new_data = self._mgr.fillna(
6049 value=value, limit=limit, inplace=inplace, downcast=downcast
6050 )
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\internals\managers.py in fillna(self, value, limit, inplace, downcast)
555
556 def fillna(self, value, limit, inplace: bool, downcast) -> "BlockManager":
--> 557 return self.apply(
558 "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast
559 )
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\internals\managers.py in apply(self, f, align_keys, **kwargs)
394 applied = b.apply(f, **kwargs)
395 else:
--> 396 applied = getattr(b, f)(**kwargs)
397 result_blocks = _extend_blocks(applied, result_blocks)
398
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\internals\blocks.py in fillna(self, value, limit, inplace, downcast)
1773 def fillna(self, value, limit=None, inplace=False, downcast=None):
1774 values = self.values if inplace else self.values.copy()
-> 1775 values = values.fillna(value=value, limit=limit)
1776 return [
1777 self.make_block_same_class(
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\arrays\base.py in fillna(self, value, method, limit)
615 # fill with value
616 new_values = self.copy()
--> 617 new_values[mask] = value
618 else:
619 new_values = self.copy()
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\arrays\masked.py in __setitem__(self, key, value)
103 if _is_scalar:
104 value = [value]
--> 105 value, mask = self._coerce_to_array(value)
106
107 if _is_scalar:
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\arrays\integer.py in _coerce_to_array(self, value)
423
424 def _coerce_to_array(self, value) -> Tuple[np.ndarray, np.ndarray]:
--> 425 return coerce_to_array(value, dtype=self.dtype)
426
427 def astype(self, dtype, copy: bool = True) -> ArrayLike:
~\AppData\Roaming\Python\Python38\site-packages\pandas\core\arrays\integer.py in coerce_to_array(values, dtype, mask, copy)
241 "mixed-integer-float",
242 ]:
--> 243 raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype")
244
245 elif is_bool_dtype(values) and is_integer_dtype(dtype):
TypeError: object cannot be converted to an IntegerDtype
最佳答案
使用numpy.where
为了避免在输出列中出现 float
:
df['new_col'] = np.where(df['B'].isna(), df.A, df.B)
print (df)
A B new_col
0 Bb00 100080 100080
1 Aa00 <NA> Aa00
2 Cc10 450089 450089
print (df['new_col'].apply(type))
0 <class 'int'>
1 <class 'str'>
2 <class 'int'>
Name: new_col, dtype: object
如果输出中需要字符串:
df['new_col'] = np.where(df['B'].isna(), df.A, df.B).astype(str)
print (df)
A B new_col
0 Bb00 100080 100080
1 Aa00 <NA> Aa00
2 Cc10 450089 450089
print (df['new_col'].apply(type))
0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
Name: new_col, dtype: object
关于python - 类型错误 : object cannot be converted to an IntegerDtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67733179/
我想用 df 中的 A 替换 B 中的 nan 值: df: A B 0 Bb00 100080 1 Aa00 2 Cc10 450089 df 数
尝试将 Pandas 中的对象(字符串)列转换为 Int32 时出现以下错误这是允许 NA 的整数类型值。 df.column = df.column.astype('Int32') TypeErro
我是一名优秀的程序员,十分优秀!