hex*_*x93 3 python dataframe pandas drop
我试图在 pandas 数据框中删除方差为 0 的列。我确信这个问题已经在某个地方得到了回答,但我在找到相关线索时遇到了很多麻烦。我找到了这个线程baseline,但是当我使用命令尝试数据框的解决方案时
baseline_filtered=baseline.loc[:,baseline.std() > 0.0]
Run Code Online (Sandbox Code Playgroud)
我收到错误
"Unalignable boolean Series provided as "
IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).
Run Code Online (Sandbox Code Playgroud)
那么,有人可以告诉我为什么会收到此错误或提供替代解决方案吗?
有一些非数字列,因此std默认删除这些列:
baseline = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,1,1,1,1,1],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})
#no A, F columns
m = baseline.std() > 0.0
print (m)
B True
C True
D False
E True
dtype: bool
Run Code Online (Sandbox Code Playgroud)
因此,添加或删除字符串列的可能解决方案是使用DataFrame.reindex:
baseline_filtered=baseline.loc[:,m.reindex(baseline.columns, axis=1, fill_value=True) ]
print (baseline_filtered)
A B C E F
0 a 4 7 5 a
1 b 5 8 3 a
2 c 4 9 6 a
3 d 5 4 9 b
4 e 5 2 2 b
5 f 4 3 4 b
baseline_filtered=baseline.loc[:,m.reindex(baseline.columns, axis=1, fill_value=False) ]
print (baseline_filtered)
B C E
0 4 7 5
1 5 8 3
2 4 9 6
3 5 4 9
4 5 2 2
5 4 3 4
Run Code Online (Sandbox Code Playgroud)
另一个想法是使用DataFrame.nunique字符串和数字列:
baseline_filtered=baseline.loc[:,baseline.nunique() > 1]
print (baseline_filtered)
A B C E F
0 a 4 7 5 a
1 b 5 8 3 a
2 c 4 9 6 a
3 d 5 4 9 b
4 e 5 2 2 b
5 f 4 3 4 b
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1911 次 |
| 最近记录: |