2016-10-19 48 views
2

如果兩列中的值的組合有效,我想替換列中的值。比方說,我有以下DataFrame搜索數據框中的組合以更改單元格值

df = pd.DataFrame([ 
     ['Texas 1', '111', '222', '333'], 
     ['Texas 1', '444', '555', '666'], 
     ['Texas 2', '777','888','999'] 
    ]) 

     0 1 2 3 
0 Texas 1 111 222 333 
1 Texas 1 444 555 666 
2 Texas 2 777 888 999 

如果我想在column 2 = 222我做column 2如果column 0 = Texas 1和值替換值如下:

df.ix[ (df.Column 0=='Texas 1')&(df.Column 2 =='222'),Column 2] = "Success" 

,對於一個工作正常幾個組合。我失去的部分是如何爲300多種組合做到這一點?我想也許我可以使用dict並存儲密鑰,這將是'Success'或任何其他價值。列表可以是組合。有點像這樣。

a["Success"] = [Texas 1, 222] 
>>> a 
{"Success": [Texas 1, 222]} 

但我不知道如何做到這一點在DataFrame

回答

1

您幾乎擁有所有的代碼,只需創建dictionarylist並對其進行迭代,即可完成。

import pandas as pd 
combinations = [['key1', 'key2', 'msg']] 
combinations.append(['Texas 1', '222', 'triple two']) 
combinations.append(['Texas 1', '555', 'triple five']) 

df = pd.DataFrame([ 
     ['Texas 1', '111', '222', '333'], 
     ['Texas 1', '444', '555', '666'], 
     ['Texas 2', '777','888','999'] 
    ]) 

for c in combinations: 
    df.ix[(df[0] == c[0]) & (df[2] == c[1]), 1] = c[2] 

輸出:

  0   1 2 3 
0 Texas 1 triple two 222 333 
1 Texas 1 triple five 555 666 
2 Texas 2   777 888 999 
+0

這給了我一直在尋找的東西。在這個特定的例子中使用字典或列表有什麼區別? – rubito

+1

在這個特定的例子中真的沒有關係。字典更方便但速度更慢,不保存順序,而列表更快,並保持順序。就語義而言,在這裏使用字典沒有意義,例如如果兩個不同的值對應該給出相同的結果呢?關鍵是什麼,價值是什麼? –

0

偉大的使用案例DataFrame.apply()。 Lamda功能一路!

df = pd.DataFrame([ 
     ['Texas 1', 111, 222, 333], 
     ['Texas 1', 444, 555, 666], 
     ['Texas 2', 777,888,999] 
    ]) 


val_dict = {} 
# assumption 
# str_like_Success : [column_0 , column_1] 
val_dict["Success"] = ['Texas 1', 222] 
val_dict["Failure"] = ['Texas 2', 888] 

功能fill_values_from_dict將被應用到每一行,其中x是行(系列)和val_dict高於

def fill_values_from_dict(x,val_dict): 
     for key,val in val_dict.items(): 
      if x[0] == val[0] and x[2] == val[1]: 
       x.set_value(1,key) 
       return x 
     return x 

創建的字典應用fill_values_from_dict於每一行

df1 = df.apply(lambda x : fill_values_from_dict(x,val_dict),axis=1) 

輸出:

print(df1) 

      0  1 2 3 
    0 Texas 1 Success 222 333 
    1 Texas 1  444 555 666 
    2 Texas 2 Failure 888 999 
相關問題