2013-11-23 56 views
0

将我的二进制d.type_str变量转换为'bid'或'ask'时出现以下错误。谢谢你们的帮助!我使用python 2.7Python字符串比较错误

我的代码:

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> 
+0

是''Series' pandas.Series'? –

+0

是的,我读了熊猫csv,该数据框系列的列标题是d.typ_str – user2113095

+0

我在 – user2113095

回答

2

正如你所说,你typestr是二进制的。熊猫抱怨当您尝试比较字符串SERISE与int数据,请参见

>>> 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' 
+0

之前添加了前几行,谢谢 – user2113095

+0

+1,不是一个很酷的答案,而是为了能够猜猜问题和错误的原意。顺便说一句,如果这是INT为字符串,那么'usd_trades ['d.type_str'] = np.choose(usd_trades ['d.type_str'],['bid','ask'])' –