2017-01-12 168 views
1

我在块从CSV这样读取数据的一些额外列:大熊猫将根据诸多条件

 for chunk in pd.read_csv(file, chunksize=50000, names = col_names, header = 0, dtype = dtype): 
      chunk['derived_field_1'] = [1 if x == 'High' else -1 for x in chunk['indicator']] 

以上的工作,它是基于一个条件。我想根据两个领域的条件来做到这一点。使值的组合的总数为8。作为一个例子

chunk['derived_field_2'] = [chunk['column_1'] if ((x == 'Red' for x in chunk['Color']) and (y == 'High' for y in chunk['Indicator'])) else 
          chunk['column_2'] if ((x == 'Green' for x in chunk['Color']) and (y == 'Low' for y in chunk['Indicator'])) else 0] 

我想要做的上述和保持与像上述6多个条件的else条件下去。这是失败的,两个for循环不起作用。我得到这个错误 -

raise ValueError('Length of values does not match length of ' 'index') 
ValueError: Length of values does not match length of index 

有人会知道这个错误的原因?

回答

2

可以使用numpy.where一个矢量的解决方案:

import numpy as np 
chunk['derived_field_2'] = (np.where((chunk['Color'] == "Red") & (chunk["Indicator"] == "High"), chunk["column_1"], 
    np.where((chunk['Color'] == "Green") & (chunk["Indicator"] == "Low"), chunk["column_2"], 0)) 
+1

感谢您的回答:) – CodeGeek123

+0

嗨,这仍然引发错误:提高ValueError异常(“值的长度不匹配的”长度“指数”) ValueError:值的长度与索引的长度不匹配。你以前面对过这个吗?我将min_itemsize设置为更高的数字,但这并不起作用 – CodeGeek123

+0

我想不出它会失败的原因。刚刚在一个小文件上测试,似乎工作正常。 – Psidom