python - 如何解决 ValueError:将行附加到 Pandas 数据时
问题描述
我有一个数据熊猫数据框和一个将一行附加到现有数据框的函数
df = pd.DataFrame()
df.columns = ['A', 'Line', 'B']
# add a new row at the end of non-indexed df
def addRow(self, colData, colNames):
l = len(df)
colList = []
for x in colData :
colList.append(str(x))
new_record = pd.DataFrame([tuple(colDList)])
new_record['Line'] = new_record['Line'].astype(int)
I am getting following error
Traceback (most recent call last):
File
line 207, in addRow
new_record[colName] = new_record[colName].astype(int)
File "site-packages/pandas/core/generic.py", line 3054, in astype
raise_on_error=raise_on_error, **kwargs)
File "python-3.6.1/linux_x86_64/lib/python3.6/site-packages/pandas/core/internals.py", line 3168, in astype
return self.apply('astype', dtype=dtype, **kwargs)
File "core/internals.py", line 3035, in apply
applied = getattr(b, f)(**kwargs)
File "site-packages/pandas/core/internals.py", line 462, in astype
values=values, **kwargs)
File "internals.py", line 505, in _astype
values = _astype_nansafe(values.ravel(), dtype, copy=True)
File "ckages/pandas/types/cast.py", line 534, in _astype_nansafe
return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)
File "pandas/lib.pyx", line 983, in pandas.lib.astype_intsafe
(pandas/lib.c:16816)
File "pandas/src/util.pxd", line 74, in util.set_value_at (pandas/lib.c:69655)
ValueError: int() 以 10 为底的无效文字:''
有人可以帮我解决价值错误吗
解决方案
同意评论中的 Sai,因为如何转换'A'
为整数,所以使用pd.to_numeric
:
new_record['Line'] = pd.to_numeric(new_record['Line'], errors='coerce')
大声笑,现在你喜欢熊猫了 :-)
推荐阅读
- excel - 如何在excel vba中将“col”值解析为Const NameCol
- android - 如何将 ABI 文件中提到的区块链合约集成到 Android 应用程序中?
- xamarin.ios - UIWebView 在出现键盘时在文本字段下方创建空白区域
- html - 在我使用 asp-route-id 和 asp-page 打开的页面中使用我使用 foreach 循环生成的代码的特定部分(img src)
- python - Sqlalchemy 石墨烯深度嵌套模式
- c# - ASP.NET MVC - 传递依赖项时的最佳实践
- sql-server - SQL CASE 多于或少于
- c++ - 初始化指向常量数组的指针
- mysql - 按名称在sql表中搜索
- r - 如何从 bioconductor(而不是 CRAN)安装软件包?