2016-09-27 2 views
4

私はさまざまな列(コーパス内の単語の頻度を示す)を持つパンダDFを持っています。各行はドキュメントに対応し、それぞれの型はfloat64型です。ワードfloat64のバイナリ化Pythonでのパンダデータフレーム

ので、上記の例が存在することを示している私はこれを2値化し、代わりに周波数のブール値(0と1 DF)で終わるする

word1 word2 word3 
0.0 0.3 1.0 
0.1 0.0 0.5 
etc 

:例えば

word1 word2 word3 
0  1  1 
1  0  1 
etc 

私はget_dummies()を見ましたが、出力が期待通りではありませんでした。

答えて

0

コード:

import numpy as np 
import pandas as pd 

""" create some test-data """ 
random_data = np.random.random([3, 3]) 
random_data[0,0] = 0.0 
random_data[1,2] = 0.0 

df = pd.DataFrame(random_data, 
    columns=['A', 'B', 'C'], index=['first', 'second', 'third']) 

print(df) 

""" binarize """ 
threshold = lambda x: x > 0 
df_ = df.apply(threshold).astype(int) 

print(df_) 

出力:

A   B   C 
first 0.000000 0.610263 0.301024 
second 0.728070 0.229802 0.000000 
third 0.243811 0.335131 0.863908 
A B C 
first 0 1 1 
second 1 1 0 
third 1 1 1 

備考:

  • get_dummies()列ごとにそれぞれ一意の値を分析しに(それぞれのユニークな値のために)新しい列が導入されましたこの値がアクティブな場合はマーク
  • =列Aに20の一意のval UEは、20個の新しい列は、1つの列が真である場合には、他の人がどんなゼロエントリのためのゼロ—とFalseではありません何のためにTrueになりますブール値にキャスト
5

偽で、追加されます。整数にキャストすると、1と0が得られます。

import io 
import pandas as pd 

data = io.StringIO('''\ 
word1 word2 word3 
0.0 0.3 1.0 
0.1 0.0 0.5 
''') 
df = pd.read_csv(data, delim_whitespace=True) 

res = df.astype(bool).astype(int) 
print(res) 

出力:

word1 word2 word3 
0  0  1  1 
1  1  0  1 
1

@Albertoガルシア-Rabosoが答えとして、私が答えているだろうが、ここで非常に迅速であり、同じ考え方を活用選択肢があります。

使用np.where

pd.DataFrame(np.where(df, 1, 0), df.index, df.columns) 

enter image description here


タイミング

enter image description here

0

はパンダのインデックスを使用して別の方法を発見しました。

これは、単にそのような単純な

df[df>0] = 1 

によって行うことができます!

関連する問題