2013-11-23 57 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'])' –