代码之家  ›  专栏  ›  技术社区  ›  The_Anil

获取无效类型比较错误

  •  1
  • The_Anil  · 技术社区  · 7 年前

    如果有人能帮助我,我得到了无效的类型比较错误?基本上,我在想用零替换数据帧中所有“-”的那一行上遇到了一个错误,以便在数值操作中保持一致。下面分别是我的代码和错误:

    代码:

    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
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Rao Sahab    7 年前

    问题就在这里

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

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

    bitcoin_market_info['Volume']=="-"
    

    就好像变量是字符串类型,然后尝试在其末尾为同一个变量分配整型值一样。

    我在猜你的变量 体积 是字符串类型,因此可以执行此操作

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

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