從任意數(shù)據(jù)框開始,我想返回一個(gè)數(shù)據(jù)框,其中僅包含具有多個(gè)不同值的那些列。我有:X = df.nunique()喜歡: Id 5 MSSubClass 3 MSZoning 1 LotFrontage 5 LotArea 5 Street 1 Alley 0 LotShape 2然后我將其從系列轉(zhuǎn)換為數(shù)據(jù)框:X = X.to_frame(name = 'dcount')然后我使用 where 子句只返回大于 1 的值:X.where(X[['dcount']]>1)看起來像: dcount Id 5.0 MSSubClass 3.0 MSZoning NaN LotFrontage 5.0 LotArea 5.0 Street NaN Alley NaN LotShape 2.0 ...但我現(xiàn)在只想要那些沒有 dcount = 'NaN' 的 column_names(在 X 的索引中),以便我最終可以返回到我的原始數(shù)據(jù)幀 df 并將其定義為:df=df[[list_of_columns]]這應(yīng)該怎么做?我嘗試了十幾種方法,這是一個(gè) PitA。我懷疑有一種方法可以用 1 或 2 行代碼來完成。
1 回答

天涯盡頭無女友
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用布爾索引并避免將計(jì)數(shù)系列轉(zhuǎn)換為數(shù)據(jù)幀:
counts = df.nunique()
df = df[counts[counts > 1].index]
關(guān)鍵是要注意您系列的索引counts是列標(biāo)簽。因此,您可以過濾系列,然后通過pd.Series.index.
這是一個(gè)演示:
df = pd.DataFrame({'A': [1, 1, 1], 'B': [1, 2, 3],
'C': [4, 5, 5], 'D': [0, 0, 0]})
counts = df.nunique()
df = df[counts[counts > 1].index]
print(df)
B C
0 1 4
1 2 5
2 3 5
添加回答
舉報(bào)
0/150
提交
取消