Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过数据帧的可能优化_Python_Pandas_Dataframe - Fatal编程技术网

Python 通过数据帧的可能优化

Python 通过数据帧的可能优化,python,pandas,dataframe,Python,Pandas,Dataframe,我试图找到一种方法来优化熊猫数据帧中的循环。该数据集包含约450k行和约20列。dataframe包含3个位置变量作为多索引,我想删除组中存在NaN列的行,否则用组的平均值填充NaN LOC = ['market_id', 'midmarket_id', 'submarket_id'] # Assign -1000 to multiindex nan values df = df.fillna({c:-1000 for c in LOC}) df = df.set_index(LOC).sor

我试图找到一种方法来优化熊猫数据帧中的循环。该数据集包含约450k行和约20列。dataframe包含3个位置变量作为多索引,我想删除组中存在NaN列的行,否则用组的平均值填充NaN

LOC = ['market_id', 'midmarket_id', 'submarket_id']

# Assign -1000 to multiindex nan values
df = df.fillna({c:-1000 for c in LOC})
df = df.set_index(LOC).sort_index(level=[i for i in range(len(LOC))])

# Looping through subset with same (market, midmarket, submarket)
for k, v in df.copy().groupby(level=[i for i in range(len(LOC))]):

    # If there is any column with all NaN value, drop it from df
    if v.isnull().all().any():
        df.drop(v.index.values)

    # If there is at least one non-NaN value, fillna with mean
    else:
        df.loc[v.index.values] = df.loc[v.index.values].fillna(v.mean())
所以如果有这样的数据帧 它应该像这样转换,删除包含所有NaN列的行

如果这是多余的或不符合堆栈溢出问题指南,我深表歉意。但如果有人有更好的解决办法,我将不胜感激


提前感谢。

无需复制整个数据帧。也不需要手动迭代
GroupBy
元素。以下是另一种解决方案:

LOC = ['market_id', 'midmarket_id', 'submarket_id']

# Assign -1000 to NaN values
df = df.fillna(-1000)

# Include only columns containing non-nulls
non_nulls = np.where(df.notnull().any())[0]
df = df.iloc[:, non_nulls]

# Fill columns with respective groupwise means
g = df.groupby(LOC)

for col in df.columns.difference(LOC):
    df[col] = df[col].fillna(g[col].transform('mean'))

3-7号线似乎什么都没做。3号线上所有的NaN都充满了-1000,所以之后什么也没有发生。然而,我应用了代码的最后两行来替换for循环,并解决了我的问题。非常感谢。