亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用sklearn解碼pandas數據幀

用sklearn解碼pandas數據幀

收到一只叮咚 2021-11-30 10:26:26
我有一個包含許多列的數據框。其中一些是字符串,另一些是整數。我使用此代碼對我的數據框進行編碼:le = LabelEncoder()for col in df.columns:    df_encoded[col] = df.apply(le.fit_transform)有效!但是當我想用這個代碼解碼它時:for col in df.columns:    df_decoded[col] = df_encoded.apply(le.inverse_transform)我收到此錯誤:ValueError: ('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()', 'occurred at index MYCOLUMNNAME')
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

數據類型因列而異,因此在這里使用applywithfit_transform不起作用。它似乎可以正常工作,但在LabelEncoder操作結束時將適合最右邊的列,因此當您嘗試應用 時inverse_transform,LabelEncoder 會將其他列中的所有元素替換為它在最右邊的列。例如:


df = pd.DataFrame([{'A': 1, 'B': 'p'}, {'A': 1, 'B': 'q'},  {'A': 2, 'B': 'o'},  {'A': 3, 'B': 'p'}])

df

   A  B

0  1  p

1  1  q

2  2  o

3  3  p


df = df.apply(le.fit_transform)

df

   A  B

0  0  1

1  0  2

2  1  0

3  2  1   # Looks fine


df.apply(le.inverse_transform)

   A  B

0  o  p

1  o  q

2  p  o

3  q  p   # Whoops

即使您一一遍歷列并執行fit_transformand ,您也會看到相同的結果inverse_transform。


在反轉之前,您需要將編碼器安裝到正確的列:


le = LabelEncoder()

df_encoded = pd.DataFrame(columns=df.columns)

df_decoded = pd.DataFrame(columns=df.columns)


for col in df.columns:

    df_encoded[col] = le.fit_transform(df[col])


df_encoded

   A  B

0  0  1

1  0  2

2  1  0

3  2  1


for col in df.columns:

    le = le.fit(df[col])

    df_decoded[col] = le.inverse_transform(df_encoded[col])


df_decoded


   A  B

0  1  p

1  1  q

2  2  o

3  3  p   # Yeay


查看完整回答
反對 回復 2021-11-30
  • 1 回答
  • 0 關注
  • 323 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號