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