2017-07-25 6 views
0

は、例えばデータフレームである:列ヘッダーはDataframeの行にありますか?ここ

cols = ["report_suite", "ProductID", "Manufacturer", "Brand Manager", "Finish"] 
data = [["rs_1", "ProductID", "Manufacturer", "Finish", np.nan], ["rs_2", 
"ProductID", "Manufacturer", "Brand Manager", "Finish"], ["rs_3", 
"Brand Manager", "Finish", np.nan, np.nan]] 
df = pd.DataFrame(data, columns = cols) 

私は何をしたい列ヘッダーは(report_suite列を含まない)データの行であるか否かについての各列のブールとピボットテーブルを持っています。私はあなたがデータフレームのインデックスを変更する方法を見つけ出すことができれば、あなたは良いですが、辞書のアプローチを使用し

cols = ["report_suite", "ProductID", "Manufacturer", "Brand Manager", "Finish"] 
data = [["rs_1", 1, 1, 0, 1], ["rs_2", 1, 1, 1, 1], ["rs_3", 0, 0, 1, 1]] 
final_df = pd.DataFrame(data, columns = cols) 

答えて

1
In [185]: df.set_index('report_suite') \ 
      .apply(lambda x: x.eq(x.name)) \ 
      .astype(np.int8) \ 
      .reset_index() 
Out[185]: 
    report_suite ProductID Manufacturer Brand Manager Finish 
0   rs_1   1    1    0  0 
1   rs_2   1    1    1  1 
2   rs_3   0    0    0  0 

または

In [191]: df.set_index('report_suite') \ 
      .fillna('') \ 
      .apply(lambda x: x.str.contains(x.name)) \ 
      .astype(np.int8) \ 
      .reset_index() 
Out[191]: 
    report_suite ProductID Manufacturer Brand Manager Finish 
0   rs_1   1    1    0  0 
1   rs_2   1    1    1  1 
2   rs_3   0    0    0  0 
+0

実際には、これは必要なものではありません。これは、行データが列ヘッダーと同じ順序である場合にのみ機能するためです。私は、列見出しがデータの行のどこにでもあるかどうかを確認する必要があります。 – Hound

+0

@Hound、テキストを「ワンホットエンコード」したいですか?あなたはあなたの "生データ"の例を作ることができますか? – MaxU

+0

列のデータがヘッダーと必ずしも一致しないので、正確には「1つのホットエンコーディング」ではありません。たとえば、2番目の行ではすべての列がヘッダーと一致しますが、3番目の行で最初の値「ブランドマネージャー」が3番目の列ヘッダーに一致します。 – Hound

0

:だから私が望む最終的な出力はこれですto go

import pandas as pd 
import numpy as np 

cols = ["report_suite", "ProductID", "Manufacturer", "Brand Manager", "Finish"] 
data = [["rs_1", "ProductID", "Manufacturer", "Finish", np.nan], ["rs_2", 
    "ProductID", "Manufacturer", "Brand Manager", "Finish"], ["rs_3", 
    "Brand Manager", "Finish", np.nan, np.nan]] 
df = pd.DataFrame(data, columns = cols) 


preprocessed_data = [] 
for item in data: 
    item.pop(0) 
    preprocessed_data.append(item) 

wordSet = set(preprocessed_data[0]).union(set(preprocessed_data[1])).union(set(preprocessed_data[2])) 

wordict1 = dict.fromkeys(wordSet,0) 
wordict2 = dict.fromkeys(wordSet,0) 
wordict3 = dict.fromkeys(wordSet,0) 

for word in preprocessed_data[0]: 
    wordict1[word] += 1 

for word in preprocessed_data[1]: 
    wordict2[word] += 1 

for word in preprocessed_data[2]: 
    wordict3[word] += 1 

dframe = pd.DataFrame([wordict1 , wordict2 , wordict3]) 
関連する問題