我有熊貓 df,它看起來像圖片: 在此處輸入影像描述
如果列中超過一半的值相同,我想洗掉任何列,但我不知道該怎么做
我嘗試使用 :pandas.Series.value_counts 但沒有運氣
uj5u.com熱心網友回復:
您可以遍歷列,在嘗試使用值計數時計算值的出現次數,并檢查它是否超過列資料的 50%。
n=len(df)
cols_to_drop=[]
for e in list(df.columns):
max_occ=df['id'].value_counts().iloc[0] #Get occurences of most common value
if 2*max_occ>n: # Check if it is more than half the len of the dataset
cols_to_drop.append(e)
df=df.drop(cols_to_drop,axis=1)
uj5u.com熱心網友回復:
您可以使用apply value_counts并獲取第一個值來獲取最大計數:
count = df.apply(lambda s: s.value_counts().iat[0])
col1 4
col2 2
col3 6
dtype: int64
因此,只需根據最大計數是否超過 half 將其轉換為掩碼len(df),然后切片:
count = df.apply(lambda s: s.value_counts().iat[0])
df.loc[:, count.le(len(df)/2)] # use 'lt' if needed to drop if exactly half
輸出:
col2
0 0
1 1
2 0
3 1
4 2
5 3
使用輸入:
df = pd.DataFrame({'col1': [0,1,0,0,0,1],
'col2': [0,1,0,1,2,3],
'col3': [0,0,0,0,0,0],
})
uj5u.com熱心網友回復:
帶壓縮的布爾切片
df.loc[:, [
df.shape[0] // s.value_counts().max() >= 2
for _, s in df.iteritems()
]]
col2
0 0
1 1
2 0
3 1
4 2
5 3
歸功于@mozway 的輸入資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/455746.html
標籤:Python python-3.x 熊猫 数据框
