2017-03-15 7 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) 
を10

ご協力いただければ幸いです。これに

答えて

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 

私は任意のコピースライスエラーを受信して​​いません。これは以前にDataFramesを作成したりマッサージしたりしたためかもしれませんが、エラーや問題なしでこれを実行しました。私はあなたの元の質問を誤解しない限り、なぜ私はそれを修正することができます投票の理由をダウン投票、そしてなぜその理由の説明を理解していない。

+0

しかし、df2内のcol2の値は変更されません。 – Annie

+0

変更されました。今すぐ動作します –

+0

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

関連する問題