如何删除使用 pd.get_dummies 使用方差作为截止值后生成的重复列
How to remove duplicate columns generated after using pd.get_dummies using their variance as cutoff
我有一个使用 pd.get_dummies 生成的数据框,如下所示:
df_target = pd.get_dummies(df_column[column], dummy_na=True,prefix=column)
其中 column 是列名,df_column 是从中提取每一列以执行某些操作的数据框。
rev_grp_m2_> 225 rev_grp_m2_nan rev_grp_m2_nan
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0
0 0 0
0 0 0
现在我对生成的每一列进行方差检查并跳过那些方差为零的列。
for target_column in list(df_target.columns):
# If variance of the dummy created is zero : append it to a list and print to log file.
if ((np.var(df_target_attribute[[target_column]])[0] != 0)==True):
df_final[target_column] = df_target[target_column]
这里由于两列相同,我得到 np.var 行的键错误。
nan 列有两个方差值:
erev_grp_m2_nan 0.000819
rev_grp_m2_nan 0.000000
理想情况下,我想选择方差非零的,drop/skip 0 var.
有人可以帮我做这个吗?
DataFrame.var
使用:
print (df.var())
rev_grp_m2_> 225 0.083333
rev_grp_m2_nan 0.000000
rev_grp_m2_nan 0.000000
使用最后一个过滤 boolean indexing
:
out = df.loc[:, df.var()!= 0]
print (out)
rev_grp_m2_> 225
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1
8 0
9 0
10 0
11 0
编辑:您可以获得非 0 值的索引,然后通过 iloc
:
选择
cols = [i for i in np.arange(len(df.columns)) if np.var(df.iloc[:, i]) != 0]
print (cols)
[0]
df = df.iloc[:, cols]
print (df)
rev_grp_m2_> 225
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1
8 0
9 0
10 0
11 0
另一个想法是如果所有值都是 0
:
则过滤掉
cols = [i for i in np.arange(len(df.columns)) if (df.iloc[:, i] != 0).any()]
out = df.iloc[:, cols]
或者:
out = df.loc[:, (df != 0).any()]
print (out)
rev_grp_m2_> 225
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1
8 0
9 0
10 0
11 0
我有一个使用 pd.get_dummies 生成的数据框,如下所示:
df_target = pd.get_dummies(df_column[column], dummy_na=True,prefix=column)
其中 column 是列名,df_column 是从中提取每一列以执行某些操作的数据框。
rev_grp_m2_> 225 rev_grp_m2_nan rev_grp_m2_nan
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
1 0 0
0 0 0
0 0 0
0 0 0
0 0 0
现在我对生成的每一列进行方差检查并跳过那些方差为零的列。
for target_column in list(df_target.columns):
# If variance of the dummy created is zero : append it to a list and print to log file.
if ((np.var(df_target_attribute[[target_column]])[0] != 0)==True):
df_final[target_column] = df_target[target_column]
这里由于两列相同,我得到 np.var 行的键错误。 nan 列有两个方差值:
erev_grp_m2_nan 0.000819
rev_grp_m2_nan 0.000000
理想情况下,我想选择方差非零的,drop/skip 0 var.
有人可以帮我做这个吗?
DataFrame.var
使用:
print (df.var())
rev_grp_m2_> 225 0.083333
rev_grp_m2_nan 0.000000
rev_grp_m2_nan 0.000000
使用最后一个过滤 boolean indexing
:
out = df.loc[:, df.var()!= 0]
print (out)
rev_grp_m2_> 225
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1
8 0
9 0
10 0
11 0
编辑:您可以获得非 0 值的索引,然后通过 iloc
:
cols = [i for i in np.arange(len(df.columns)) if np.var(df.iloc[:, i]) != 0]
print (cols)
[0]
df = df.iloc[:, cols]
print (df)
rev_grp_m2_> 225
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1
8 0
9 0
10 0
11 0
另一个想法是如果所有值都是 0
:
cols = [i for i in np.arange(len(df.columns)) if (df.iloc[:, i] != 0).any()]
out = df.iloc[:, cols]
或者:
out = df.loc[:, (df != 0).any()]
print (out)
rev_grp_m2_> 225
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1
8 0
9 0
10 0
11 0