Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

python - Pandas DataFrame, How do I remove all columns and rows that sum to 0

I have a dataFrame with rows and columns that sum to 0.

    A   B   C    D
0   1   1   0    1
1   0   0   0    0 
2   1   0   0    1
3   0   1   0    0  
4   1   1   0    1 

The end result should be

    A   B    D
0   1   1    1
2   1   0    1
3   0   1    0  
4   1   1    1 

Notice the rows and columns that only had zeros have been removed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

df.loc[row_indexer, column_indexer] allows you to select rows and columns using boolean masks:

In [88]: df.loc[(df.sum(axis=1) != 0), (df.sum(axis=0) != 0)]
Out[88]: 
   A  B  D
0  1  1  1
2  1  0  1
3  0  1  0
4  1  1  1

[4 rows x 3 columns]

df.sum(axis=1) != 0 is True if and only if the row does not sum to 0.

df.sum(axis=0) != 0 is True if and only if the column does not sum to 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...