如何应用熊猫.DataFrame.dropna 位于具有 inplace = True 且轴 = 1 的列子集上?


import pandas as pd
df = pd.DataFrame({
'col1': [99, None, 99], 
'col2': [4, 5, 6], 
'col3': [7, None, None]})
col_list = ['col1', 'col2']
df[col_list].dropna(axis=1, thresh=2, inplace = True)

这将返回警告并使数据帧保持不变:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

以下内容不会生成警告,但仍保持数据帧不变。

df.loc[:,col_list].dropna(axis=1, thresh=2, inplace=True) 

问题:

  1. 从用户指定的列列表中,从数据帧中删除那些具有小于"thresh"非空值的列。不对不在列表中的列进行任何更改。
  2. 我需要使用 inplace=True 来避免复制数据帧,因为它很大

我不能遍历列并一次应用一列,因为熊猫。Series.dropna没有"thresh"参数。

有趣的是,dropna不支持此功能,但有一个解决方法。

v = df[col_list].notna().sum().le(2)    # thresh=2 
df.drop(v.index[v], axis=1, inplace=True)

顺便一提

我需要使用 inplace=True 来避免创建数据帧的副本

很抱歉地通知您,即使使用inplace=True,也会生成一个副本。唯一的区别是副本被就地分配回原始对象,因此不会返回新对象。

我认为问题df['col_list']或者切片创建了一个新的 df 并在该 df 上而不是对原始 dfinplace=True效果。

您可能必须使用dropna的参数subset并将列列表传递给它。

df.dropna(axis=1, thresh=2, subset=col_list,inplace = True)

相关内容

最新更新