本文介绍了将数据框用作.fillna()的参数时,是否需要相同的形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,您可以将数据框用作.fillna()的值参数

According to the Docs, you can use a Dataframe as the value parameter for .fillna()

http://pandas.pydata.org /pandas-docs/dev/generation/pandas.DataFrame.fillna.html

但是数据框是否需要相同的形状?如果是这样,为什么第一个示例给我想要的输出?

But does the dataframe need to be identical shape? If so, why does the first example give me the desired output?

使用此df:

mukey   hzdept_r    hzdepb_r    sandtotal_r silttotal_r
425897      0         61        
425897      61        152          5.3         44.7
425911      0         30           30.1        54.9
425911      30        74           17.7        49.8
425911      74        84        

我可以跑步:

df = pd.read_clipboard()
df1 = df.set_index('mukey')
df1.fillna(df.groupby('mukey').mean(),inplace=True)

和df1产生所需的df:

and df1 results in the desired df:

        hzdept_r  hzdepb_r  sandtotal_r  silttotal_r
mukey                                               
425897         0        61          5.3        44.70
425897        61       152          5.3        44.70
425911         0        30         30.1        54.90
425911        30        74         17.7        49.80
425911        74        84         23.9        52.35

但是,当我尝试在较大的df上运行相同的代码时,它会因InvalidIndexError而中断.

However, when I try to run the same code on a larger df, it breaks with InvalidIndexError.

df = pd.read_csv('www004.csv')
df1 = df.set_index('mukey')
df1.fillna(df.groupby('mukey').mean(),inplace=True)

错误:

InvalidIndexError                         Traceback (most recent call last)
<ipython-input-126-a1038ea351c9> in <module>()
----> 1 df1.fillna(df.groupby('mukey').mean(),inplace=True)

/Users/liamfoley/anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in fillna(self, value, method, axis, inplace, limit, downcast)
   2410                                              downcast=downcast)
   2411             elif isinstance(value, DataFrame) and self.ndim == 2:
-> 2412                 new_data = self.where(self.notnull(), value)
   2413             else:
   2414                 raise ValueError("invalid fill value with a %s" % type(value))

/Users/liamfoley/anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in where(self, cond, other, inplace, axis, level, try_cast, raise_on_error)
   3306                         not all([other._get_axis(i).equals(ax)
   3307                                  for i, ax in enumerate(self.axes)])):
-> 3308                     raise InvalidIndexError
   3309 
   3310             # slice me out of the other

InvalidIndexError: 

我可以通过创建一个具有相同形状的means_df来解决此问题.

I can get around that by creating a means_df that has identical shape.

import pandas as pd
df = pd.read_csv('www004.csv').set_index('mukey')
means = df.groupby(level=0).mean()
means_df = pd.merge(pd.DataFrame(df.index),means,
                    left_on='mukey',right_index=True,how='left').set_index('mukey')
df1 = df.fillna(means_df)

那给了我想要的结果:

 df.ix[426184]
        hzdept_r  hzdepb_r  sandtotal_r  silttotal_r  claytotal_r  om_r
mukey                                                                  
426184         0        18         30.1         54.9           15   3.5
426184        18        46         58.2         17.8           24   NaN
426184        46       152          NaN          NaN            5   NaN

df1.ix[426184]
        hzdept_r  hzdepb_r  sandtotal_r  silttotal_r  claytotal_r  om_r
mukey                                                                  
426184         0        18        30.10        54.90           15   3.5
426184        18        46        58.20        17.80           24   3.5
426184        46       152        44.15        36.35            5   3.5

相关:熊猫从另一个数据框中填充数据框中的缺失值

在熊猫数据框中填写缺失的行值

在Pandas中,我该如何用另一个具有相似索引的数据框的值来修补缺少值的数据框?

推荐答案

一种解决方法是使用变换(而不是汇总)groupby方法:

A workaround for this could be to use a transform (rather than an aggregating) groupby method:

df1.fillna(df1.groupby(level=0).transform("mean"))

目前尚不清楚这是否是熊猫中的错误,我建议在Github上发布一个问题(这可能是一个不错的功能)!

这篇关于将数据框用作.fillna()的参数时,是否需要相同的形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 16:27