gpt4 book ai didi

python - 不存在数据行时的插值

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:48 25 4
gpt4 key购买 nike

我有一个看起来像这样的数据框

     Idnumber   Parent  Date             Other variables
1 a 2005 x
1 a 2007 x
2 b 2005 x
2 b 2006 x
2 b 2007 x

我需要它看起来像这样:

     Idnumber   Parent   Date          Other variables           
1 a 2005 x
1 NaN 2006 NaN
1 a 2007 x
2 b 2005 x
2 b 2006 x
2 b 2007 x

考虑到我需要稍后能够对添加的值进行检查,我不能简单地添加它们。我需要验证它们不存在并复制各种剩余的变量,这些变量将被插值。这些需要清空。

我的想法是在所有现有行之间创建一个空行,然后简单地向后和向前填充。从而确保没有其他信息被复制。但我不知道该怎么做。

我最好跳过空行的介绍,一次性完成整个事情。但我更不知道如何开始

最佳答案

对于整体方法,您可以首先定义应该存在哪些行,然后与原始数据集合并。

>>> orig

Idnumber Parent Date Other
0 1 a 2005 x
1 1 a 2007 x
2 2 b 2005 x
3 2 b 2006 x
4 2 b 2007 x

现在使用itertools.product来定义应该存在的所有行。 (您也可以使用pd.MultiIndex.from_product。)

>>> import itertools
>>> df = pd.DataFrame(list(itertools.product(orig['Idnumber'].unique(),
orig['Date'].unique())))
>>> df.columns = ['Idnumber','Date']

Idnumber Date
0 1 2005
1 1 2006
2 1 2007
3 2 2005
4 2 2006
5 2 2007

然后与原始数据合并:

>>> df.merge(orig,how='outer',on=['Idnumber','Date'])

Idnumber Date Parent Other
0 1 2005 a x
1 1 2006 NaN NaN
2 1 2007 a x
3 2 2005 b x
4 2 2006 b x
5 2 2007 b x

在此之后,您可以使用 fillnainterpolate 等。

关于python - 不存在数据行时的插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35510289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com