我有一个dataFrame
熊猫,其中几列都有空值。是否有内置函数可以让我删除这些列?
问问题
86447 次
4 回答
116
是的,dropna
。请参阅http://pandas.pydata.org/pandas-docs/stable/missing_data.html和DataFrame.dropna
文档字符串:
Definition: DataFrame.dropna(self, axis=0, how='any', thresh=None, subset=None)
Docstring:
Return object with labels on given axis omitted where alternately any
or all of the data are missing
Parameters
----------
axis : {0, 1}
how : {'any', 'all'}
any : if any NA values are present, drop that label
all : if all values are NA, drop that label
thresh : int, default None
int value : require that many non-NA values
subset : array-like
Labels along other axis to consider, e.g. if you are dropping rows
these would be a list of columns to include
Returns
-------
dropped : DataFrame
要运行的具体命令是:
df=df.dropna(axis=1,how='all')
于 2012-06-02T04:52:48.933 回答
0
这是一个简单的函数,您可以通过传递数据帧和阈值直接使用它
df
'''
pets location owner id
0 cat San_Diego Champ 123.0
1 dog NaN Ron NaN
2 cat NaN Brick NaN
3 monkey NaN Champ NaN
4 monkey NaN Veronica NaN
5 dog NaN John NaN
'''
def rmissingvaluecol(dff,threshold):
l = []
l = list(dff.drop(dff.loc[:,list((100*(dff.isnull().sum()/len(dff.index))>=threshold))].columns, 1).columns.values)
print("# Columns having more than %s percent missing values:"%threshold,(dff.shape[1] - len(l)))
print("Columns:\n",list(set(list((dff.columns.values))) - set(l)))
return l
rmissingvaluecol(df,1) #Here threshold is 1% which means we are going to drop columns having more than 1% of missing values
#output
'''
# Columns having more than 1 percent missing values: 2
Columns:
['id', 'location']
'''
现在创建不包括这些列的新数据框
l = rmissingvaluecol(df,1)
df1 = df[l]
PS:您可以根据您的要求更改阈值
奖励步骤
您可以找到每列缺失值的百分比(可选)
def missing(dff):
print (round((dff.isnull().sum() * 100/ len(dff)),2).sort_values(ascending=False))
missing(df)
#output
'''
id 83.33
location 83.33
owner 0.00
pets 0.00
dtype: float64
'''
于 2019-06-19T15:15:45.507 回答
0
另一种解决方案是在非空位置创建一个具有 True 值的布尔数据框,然后获取具有至少一个 True 值的列。这将删除具有所有 NaN 值的列。
df = df.loc[:,df.notna().any(axis=0)]
如果要删除具有至少一个缺失 (NaN) 值的列;
df = df.loc[:,df.notna().all(axis=0)]
这种方法在删除包含空字符串、零或基本上任何给定值的列时特别有用。例如;
df = df.loc[:,(df!='').all(axis=0)]
删除具有至少一个空字符串的列。
于 2021-05-12T23:33:15.603 回答
-2
从数据框中删除所有空列的功能:
def Remove_Null_Columns(df):
dff = pd.DataFrame()
for cl in fbinst:
if df[cl].isnull().sum() == len(df[cl]):
pass
else:
dff[cl] = df[cl]
return dff
此函数将从 df 中删除所有 Null 列。
于 2018-06-29T06:41:01.610 回答