2017-04-14 94 views
2

我有以下問題,其中我的Python代碼不起作用。希望能提出一些建議,說明爲什麼以及如何解決。Python:在複雜數組上查找每行的多列搜索

這裏的例子數據框:

 
cust_id max_nibt nibt_0 nibt_1 nibt_10 line_0 line_1 line_10 
11 200 -5 200 500 100 200 300 
22 300 -10 100 300 100 200 300 
33 400 -20 0 400 100 200 300 
for i in range (0,11): 
    if (df4['nibt_%s' % i] == df4['max_nibt']): 
     df4['model_line'] = df4['line_%s' % i] 

的代碼給我下面的錯誤:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

然而,當我使用.any(),它只是給了我最後的範圍內分配model_line = line_10。當我使用.all()時,所有cust_ids的答案都是一樣的。想法?提前致謝。

回答

1

你不能比較這樣的系列,因爲大熊貓如何知道你想要比較哪些元素?

如果我理解正確的話,你可以這樣做:

for i in range(0,11): 
    for j,k in df.iterrows(): 
    if k['nibt_%s' % i] == k['max_nibt']: 
     df.iloc[j]['model_line'] = df.iloc[j]['line_%s' % i] 
2

考慮使用.loc的行索引條件句。由於是,你for循環比較平等,因此任何數量的布爾結果的兩列(即,熊貓系列)的所有值:

for i in [0,1,10]: 
    df4.loc[df4['nibt_%s' % i] == df4['max_nibt'], 'model_line'] = df4['line_%s' % i] 

或者,因爲這for循環可以覆蓋相同的新列,model_line,考慮增加model_line的後綴版本:

for i in [0,1,10]: 
    df4.loc[df4['nibt_%s' % i] == df4['max_nibt'], 'model_line_%s' % i] = df4['line_%s' % i] 
+0

這完美地工作!謝謝!。 – Timmy

+0

太棒了!樂意效勞。當我從熊貓開始時,這個錯誤可能是我遇到的最常見的錯誤。請確認接受最有用的答案(勾選標記到旁邊)以確認解決方案(甚至可以幫助未來的讀者)。 – Parfait

4

我有你想要的猜測,但你顯然不使用pd.Series正確......看到here FO更好的解釋。

IIUC
你想從line_x價值觀,以填補在nibt_x等於​​

# filter to get `nibt` columns and find the first column that equals max 
nibt_maxes = df.filter(regex='nibt_\d+').eq(df.max_nibt, 0).idxmax(1) 

# swap out the string `nibt` with `line` 
lines = nibt_maxes.replace('nibt', 'line', regex=True) 

# use `lookup` and assign values 
df['model'] = df.lookup(lines.index, lines.values) 

    cust_id max_nibt nibt_0 nibt_1 nibt_10 line_0 line_1 line_10 model 
0  11  200  -5  200  500  100  200  300 200 
1  22  300  -10  100  300  100  200  300 300 
2  33  400  -20  0  400  100  200  300 300 
+2

幹得好!矢量化版本。在我的熊貓工具箱中添加'lookup'! – Parfait

+0

謝謝@Pfafait – piRSquared