2016-05-25 5 views
4

マイパンダのデータフレーム:パイソン:SettingWithCopyWarningは:値は、データフレームからスライスのコピーに設定されるようにしようとしている

dframe = pd.DataFrame({"A":list("abcde"), "B":list("aabbc"), "C":[1,2,3,4,5]}, index=[10,11,12,13,14]) 

    A B C 
10 a a 1 
11 b a 2 
12 c b 3 
13 d b 4 
14 e c 5 

マイ所望の出力:

A B C a b c 
10 a a 1 1 None None 
11 b a 2 2 None None 
12 c b 3 None 3 None 
13 d b 4 None 4 None 
14 e c 5 None None 5 

アイデアが新しい作成することです'B'列の値に基づいて列を作成し、それぞれの値を 'C'列にコピーして新しく作成した列に貼り付けます。 ここに私のコードです:3.xでこのコードは、Python 2.7でうまく

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame 

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy 
    app.launch_new_instance() 

ではなく、私はこのエラーになってしまった

lis = sorted(list(dframe.B.unique())) 

#creating empty columns 
for items in lis: 
    dframe[items] = None 


#here copy and pasting 
    for items in range(0, len(dframe)): 
     slot = dframe.B.iloc[items] 
     dframe[slot][items] = dframe.C.iloc[items] 

どこが間違っているの?

dframe = pd.concat([dframe, to_be_appended], axis=1) 

連結次に

to_be_appended = pd.get_dummies(dframe.B).replace(0, np.nan).mul(dframe.C, axis=0) 

答えて

1

スタートのようになります。検索するため

print dframe 

    A B C a b c 
10 a a 1 1.0 NaN NaN 
11 b a 2 2.0 NaN NaN 
12 c b 3 NaN 3.0 NaN 
13 d b 4 NaN 4.0 NaN 
14 e c 5 NaN NaN 5.0 

ノート。

これは、1つのホットエンコーディングとブロードキャスト乗算を組み合わせたものです。

+0

非常に簡単! 0よりもむしろNoneを得る考え? – ramesh

+1

「NaN」を含むように編集されました – piRSquared

0

Chained assignment will now by default warn if the user is assigning to a copy.

このオプションは昇給/警告/なしあり許され、オプションmode.chained_assignmentで変更することができます。ドキュメントを参照してください。 DFC =データフレーム({ 'A':[ 'AAA'、 'BBB'、 'C​​CC']、 'B':[1,2,3]})

[5]で

[6]:pd.set_option( 'chained_assignment'、 'warn')

これが試行された場合、次の警告/例外が表示されます。 [7]では

:dfc.loc [0] [ 'A'] = 1111

トレースバック(最新の呼び出しの最後) ... SettingWithCopyWarning: 値に設定されるようにしようとしていますDataFrameからのスライスのコピー。 代わりに.loc [row_index、col_indexer] = valueを使用してみてください ここに正しい割り当て方法があります。 [8]において

:DFC

A B 

1 BBB 2

:dfc.loc [0は、 'A']は[9]で11

を=

2 ccc 3

関連する問題