2017-03-15 153 views
0

我想設置一個列的值的基礎上另一列值的熊貓數據框一定的值,選擇大熊貓數據幀的頭幾行與列

df2.loc[df2['col1',len] == val, 'col2'] = df1['col2'] 

上面的代碼工作正常,然而,現在的問題是,我想設置值僅適用於第幾行,類似下面:

len1 = len(df1.index) 
df2.loc[df2['col1',len1] == val, 'col2'] = df1['col2'] 

但我得到以下錯誤:

Traceback (most recent call last): 
    File "...\lib\site-packages\pandas\indexes\base.py", line 1945, in get_loc 
    return self._engine.get_loc(key) 
    File "pandas\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\index.c:4154) 
    File "pandas\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\index.c:4018) 
    File "pandas\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12368) 

任何幫助將不勝感激。

回答

1

它改成這樣:

df2.iloc[:len(df1.index),].ix[df2.col1 == val, 'col2'] = df1['col2'] 

這是工作不知道什麼地方錯了。

name gender age occupation years_of_school married 
0 Bob  M 37 Dentist    20  N 
1 Sally  F 21 Student    16  N 
2 Jim  M 55 Carpenter    12  Y 
3 Dan  M 27 Teacher    18  Y 
4 Rose  F 14 Student    9  N 
5 Emily  F 65 Retired    22  Y 



    age_range 
0  mid 
1  young 
2  old 
3  young 
4  young 

這裏是它的樣本查詢:

df.iloc[:len(df1.index),].ix[df.age > 25, 'occupation'] = df1['age_range'] 

下面是它返回:

name gender age occupation years_of_school married 
0 Bob  M 37  mid    20  N 
1 Sally  F 21 Student    16  N 
2 Jim  M 55  old    12  Y 
3 Dan  M 27  young    18  Y 
4 Rose  F 14 Student    9  N 
5 Emily  F 65 Retired    22  Y 

我沒有收到任何複製片錯誤。這可能是因爲您之前創建或按摩了您的DataFrame,但我只是這樣做了,沒有錯誤,沒有任何問題。除非我誤解了你原來的問題,那麼我不明白爲什麼會倒票,甚至沒有解釋爲什麼倒退投票,以便我可以修復它。

+0

但它不會更改df2內col2的值。 – Annie

+0

改變它,現在應該工作 –

+0

http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy – Annie