如何申请Pandas.DataFrame.dropna在inplace=True且axis=1的列子集上?

2024-05-21 00:54:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

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

^{pr2}$

下面的代码不会生成警告,但仍然保持DataFrame不变。在

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

问题:

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

我不能在列上循环,一次只应用一列dropna,因为熊猫.Series.dropna没有“thresh”参数。在


Tags: nonetrue警告dataframedf列表collist
2条回答

我认为问题是df['col_list']或者切片创建了一个新的df,inplace=True对该df而不是原始df产生影响。在

您可能需要使用subset参数,并将列列表传递给它。在

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

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

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

顺便说一句

I need to use inplace=True to avoid making a copy of the dataframe

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

相关问题 更多 >