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
194 views
in Technique[技术] by (71.8m points)

Drop columns tha thave a header but all rows are empty Python 3 & Pandas

I just could not figure this one out:

df.dropna(axis = 1, how="all").dropna(axis= 0 ,how="all")

All headers have data. How can I exclude the headers form a df.dropna(how="all") command. I am afraid this is going to be trivial, but help me out guys.

Thanks, Levi

question from:https://stackoverflow.com/questions/65847730/drop-columns-tha-thave-a-header-but-all-rows-are-empty-python-3-pandas

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

1 Reply

0 votes
by (71.8m points)

Okay, as I understand what you want is as follows:

  • drop any column where all rows contain NaN
  • drop any row in which one or more NaN appear

So for example, given a dataframe df like:

    Id  Col1    Col2    Col3    Col4
0   1   25.0    A   NaN 6
1   2   15.0    B   NaN 7
2   3   23.0    C   NaN 8
3   4   5.0 D   NaN 9
4   5   NaN E   NaN 10

convert the dataframe by:

df.dropna(axis = 1, how="all", inplace= True)
df.dropna(axis = 0, how='all', inplace= True)

which yields:

    Id  Col1    Col2    Col4
0   1   25.0    A   6
1   2   15.0    B   7
2   3   23.0    C   8
3   4   5.0     D   9
4   5   NaN     E   10

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

...