python - 收到无效类型比较错误

标签 python python-3.x data-mining

我收到无效类型比较错误,有人可以帮忙吗?基本上,我在行上遇到错误,我想将数据框中的所有“-”替换为零,以便使其对于数值操作统一。以下分别是我的代码和错误:

代码:

import quandl, math
import numpy as np
import pandas as pd
from sklearn import preprocessing, cross_validation, svm
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

import time
import seaborn as sns
import matplotlib.pyplot as plt
import datetime
from matplotlib import style
style.use('ggplot')

# get market info for bitcoin from the start of 2016 to the current day
bitcoin_market_info = pd.read_html("https://coinmarketcap.com/currencies/ethereum/historical-data/?start=20130428&end="+time.strftime("%Y%m%d"))[0]
# convert the date string to the correct date format
bitcoin_market_info = bitcoin_market_info.assign(Date=pd.to_datetime(bitcoin_market_info['Date']))
# when Volume is equal to '-' convert it to 0
#In the line below I am getting error
bitcoin_market_info.loc[bitcoin_market_info['Volume']=="-",'Volume']=0
# convert to int
bitcoin_market_info['Volume'] = bitcoin_market_info['Volume'].astype('int64')

bitcoin_market_info.set_index('Date', inplace=True)
bitcoin_market_info = bitcoin_market_info.reindex(index=bitcoin_market_info.index[::-1])
# look at the first few rows
bitcoin_market_info.head()

错误:

F:\Anaconda3\lib\site-packages\pandas\core\ops.py:798: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
result = getattr(x, name)(y)
Traceback (most recent call last):
File "C:/Users/The_Anil/Desktop/fvsffsf.py", line 20, in <module>
bitcoin_market_info.loc[bitcoin_market_info['Volume']=="-",'Volume']=0
File "F:\Anaconda3\lib\site-packages\pandas\core\ops.py", line 861, in wrapper
res = na_op(values, other)
File "F:\Anaconda3\lib\site-packages\pandas\core\ops.py", line 800, in na_op
raise TypeError("invalid type comparison")
TypeError: invalid type comparison

最佳答案

问题就在这里

bitcoin_market_info.loc[bitcoin_market_info['Volume']=="-",'Volume']=0

您正在将它与字符串进行比较

bitcoin_market_info['Volume']=="-"

就好像变量是字符串类型,然后尝试将整数类型值分配给其末尾的同一变量。

我猜你的变量Volume是字符串类型,所以你可以这样做

bitcoin_market_info.loc[bitcoin_market_info['Volume']=="-",'Volume']="0"

然后你可以将变量转换为整数类型

关于python - 收到无效类型比较错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49292137/

相关文章:

python - 在 CentOS 上为 Django 项目安装 python 3.6 mysqlclient

algorithm - 有人可以解释如何使用 Ward 的方法来初始化 k-means 吗?

matlab - 在 K-Means 算法中使用绝对 PIL 逊相关作为距离 (MATLAB)

python - 为什么我的 python 方法在尝试打印出该方法返回的字符串时打印出 'None'?

python - 使用预训练的 Inception_v4 模型

python - Tensorflow Keras RMSE 指标返回的结果与我自己构建的 RMSE 损失函数不同

csv - 快速矿工: CSV with real numbers with commas instead of dots

python - 限制 Pandas Pivot 中的列值

python - cvtColor “code”用于16位灰度图像

python-3.x - 将 numpy 数组通过管道传输到虚拟视频设备