python - Pandas fillna 来自平均值和多列的 groupby

标签 python pandas

我正在尝试对多个列进行分组并同时填充多个列。我附上了数据的图片以及我遇到问题的代码。这是我创建的示例数据,反射(reflect)了实际数据,因为它是 secret 的。

有 4 列:名称、植物、长度和宽度。有 3 种不同类型的植物。最后 3 种植物中的每一种都缺少数据。我的最终目标是创建一个模型来猜测缺少哪些植物类型。但要做到这一点,我首先尝试将每个名称/植物组合的长度和宽度的平均值估算为它们的缺失值。

下面显示了一个计算有效平均值的示例,我失败的是插入它们来填充 na 值。

lengthmean = df.groupby(['name', 'plant']).length.mean()
print(lengthmean)

我得到的结果看起来像这样

name    plant  

Brian   plant 3    2.500000
        plant1     1.850000
        plant2     2.450000
Jeff    plant 3    4.100000
        plant1     2.333333
        plant2     2.100000
Justin  plant 3    2.900000
        plant1     1.900000
        plant2     2.850000
Zach    plant 3    1.750000
        plant1     2.650000
        plant2     3.300000

我还尝试一次执行多个列(在本例中是长度和宽度,但在我的真实数据中它不止于此)。下面是对我来说失败的代码。

df[['length','width']] = df.groupby(['name', 'plant'])['length','width']\
    .transform(lambda x: x.fillna(x.mean()))

我收到此错误'ValueError:长度不匹配:预期轴有 32 个元素,新值有 40 个元素'

非常感谢您的帮助,谢谢!

example of data

最佳答案

感谢您提供示例数据,这确实很有帮助!

看起来问题是由于您的 plant 列具有 NaN 造成的。当我运行您的代码时 df[['length','width']] = df.groupby(['name', 'plant'])['length','width']\ .transform(lambda x: x.fillna(x.mean())) 在数据集上,我确实收到了您的错误消息。

当我删除 plant 列中的空值时,它工作正常:

df = df.dropna(subset=['plant'])
df_cleaned[['length','width']] = df_cleaned.groupby(['name', 'plant'])['length','width']\
    .transform(lambda x: x.fillna(x.mean()))

如果您想填充/删除它/添加新的植物值/等等,您需要弄清楚要如何处理空植物列。

希望有帮助!

关于python - Pandas fillna 来自平均值和多列的 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59001622/

相关文章:

python - Pandas 合并数据框,删除值未出现在所有初始数据框中的行

python - 如何将具有字符串和大量(数字)的列分成两列

python - 在 fedora 19 上从源代码构建 matplotlib,没有发现 freetype 头文件

python - 在 Python 中替换 SVG 的内部内容

python - 可读套接字在recv上超时

python - 根据列值 Pandas 对 group by 进行操作

python - 在 Python Pandas 中合并两个数据集

Python- Pandas : number/index of the minimum value in the given row

python - 如何测试容器中所有元素的值(value)?

python - pandas.merge : match the nearest time stamp >= the series of timestamps