Python字符串比较错误

时间:2013-11-23 23:55:27

标签: python string types pandas

将二进制d.type_str变量转换为'bid'或'ask'时出现以下错误。谢谢你的帮助!我正在使用python 2.7

我的代码:

from itertools import izip_longest
import itertools
import pandas 
import numpy as np

all_trades = pandas.read_csv('C:\\Users\\XXXXX\\april_trades.csv', parse_dates=[0], index_col=0)
usd_trades = all_trades[all_trades['d.currency'] == 'USD']

volume = (usd_trades['d.amount_int'])
trades = (usd_trades['d.price_int'])

def cleanup(x):
    if isinstance(x, str) and 'e-' in x:
        return 0
    else:
        return float(x)

volume = volume.apply(lambda x: cleanup(x))
volume = volume.astype(float32)

##### 
typestr = (usd_trades['d.type_str'])
typestr[typestr == 'bid'] = 0 
typestr[typestr == 'ask'] = 1

错误输出:

>>> typestr[typestr == 'ask'] = 1
  File "C:\Anaconda\lib\site-packages\pandas\core\series.py", line 240, in wrapper
    % type(other))
TypeError: Could not compare <type 'str'> type with Series
>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

1 个答案:

答案 0 :(得分:2)

正如您所说,您的typestr是二进制的。当您尝试将字符串与系列与int数据进行比较时,Pandas会抱怨,请参阅

>>> s = pd.Series([1], dtype=np.int64)
>>> s == 'a'
Traceback (most recent call last):
   ...
TypeError: Could not compare <type 'str'> type with Series

从你的文字中我想你想做而不是

>>> typestr[typestr == 1] = 'ask'