
[英]How to delete the rows in pandas where all the column values are null except first three columns?
[英]Pandas - Get count of rows where all values are null except for a set of columns
你可以试试:
# specific columns
cols = ['col1','col2']
df[df.drop(cols, axis=1).isna().all(1)]
那不会检查您是否在cols
中有数据。 如果你需要,你可以这样做:
other_nan = df.drop(cols, axis=1).isna().all(1)
chosen_notna = df[cols].notna().any(1)
df[other_nan & chosen_notna]
这是一个 function 用于这样做。 我使用difference
查找获取不包括指定列的 dataframe,然后使用isna()
和all()
查找空行:
def null_rows(df, exclude=None):
exclude = [] if exclude is None else exclude
return df[df[df.columns.difference(exclude)].isna().all(1)]
例子:
df = pd.DataFrame({'col1': [None, 3, None, 8],
'col2': [1, None, 6, None],
'col3': [2, 4, 7, None],
'col4': [None, None, None, None],
'col5': [None, 5, None, None]})
print(null_rows(df, ['col2', 'col3']))
Output:
col1 col2 col3 col4 col5
0 NaN 1.0 2.0 None NaN
2 NaN 6.0 7.0 None NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.