我有一個資料框,需要洗掉每列中包含超過 55% 重復/重復值的所有列。
任何人都可以幫助我如何做到這一點?
uj5u.com熱心網友回復:
請試試這個:
讓 df1 成為您的資料框:
drop_columns = []
drop_threshold = 0.55 #define the percentage criterion for drop
for cols in df1.columns:
df_count = df1[cols].value_counts().reset_index()
df_count['drop_percentage'] = df_count[cols]/df1.shape[0]
df_count['drop_criterion'] = df_count['drop_percentage'] > drop_threshold
if True in df_count.drop_criterion.values:
drop_columns.append(cols)
df1 = df1.drop(columns=drop_columns,axis=1)
uj5u.com熱心網友回復:
讓我們使用pd.Series.duplciated:
cols_to_keep=df.columns[df.apply(pd.Series.duplicated).mean() <= .55]
df[cols_to_keep]
uj5u.com熱心網友回復:
如果您指的是最常見的值在超過 55% 或行中重復的列,這里有一個解決方案
from collections import Counter
# assuming some DataFrame named df
bool_idx = df.apply(lambda x: max(Counter(x).values()) < len(x) * .55, axis=0)
df = df.loc[:, bool_idx]
如果您在談論非唯一值,則可以使用:
bool_idx = df.apply(
lambda x: sum(
y for y in Counter(x).values() if y > 1
) < .55 * len(x),
axis=0
)
df = df.loc[:, bool_idx]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/439398.html
標籤:Python python-3.x 熊猫 数据框
