kaggleで使う機能集
Posted on 2019/08/29 in kaggle , Updated on: 2019/08/29
(まとめ中)
kaggleコンペ参加時に利用する pandas などの機能をなんども調べることが面倒なため、備忘として。
ユニークな値を探す¶
.unique()
メソッド。Seriesのみで使える。DataFrameでは使えない。numpy array を返す。
In [ ]:
df['column'].unique()
カラムの NaN の数¶
isna()
で各値が NaN か True/False を返し、sum(axis=1)
で True の数をカウント。axis=0 だと行でカウント。
In [ ]:
df['column'].isna().sum(axis=1)
pandas.agg¶
In [1]:
import pandas as pd
import numpy as np
df = pd.DataFrame([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[np.nan, np.nan, np.nan]],
columns=['A', 'B', 'C'])
df
Out[1]:
In [2]:
df.agg(['sum', 'min'])
Out[2]:
In [3]:
df.agg({'A' : ['sum', 'min'], 'B' : ['min', 'max']})
Out[3]:
In [ ]:
df.agg("mean", axis="columns")
# 0 2.0
# 1 5.0
# 2 8.0
# 3 NaN
# dtype: float64
DataFrame の全ての列を表示¶
In [ ]:
pd.set_option('display.max_columns', None)
label encoder¶
In [ ]:
if train_df[col].dtype=='O':
print(col)
train_df[col] = train_df[col].fillna('unseen_before_label')
test_df[col] = test_df[col].fillna('unseen_before_label')
train_df[col] = train_df[col].astype(str)
test_df[col] = test_df[col].astype(str)
le = LabelEncoder()
le.fit(list(train_df[col])+list(test_df[col]))
train_df[col] = le.transform(train_df[col])
test_df[col] = le.transform(test_df[col])
train_df[col] = train_df[col].astype('category')
test_df[col] = test_df[col].astype('category')
In [ ]:
for col in i_cols:
temp_df = pd.concat([train_df[[col]], test_df[[col]]])
fq_encode = temp_df[col].value_counts(dropna=False).to_dict()
train_df[col+'_fq_enc'] = train_df[col].map(fq_encode)
test_df[col+'_fq_enc'] = test_df[col].map(fq_encode)
全ての特徴量のユニークな値(固有な値)の数と、その値を全て表示
In [ ]:
for col, values in df_train.iteritems():
num_uniques = values.nunique()
print ('{name}: {num_unique}'.format(name=col, num_unique=num_uniques))
print (values.unique())
print ('\n')