从另一个datafram更新dataframe中缺少的值

2024-05-19 11:03:00 发布

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

我有丢失值的数据帧。我需要用两种方法更新丢失的值。 1基于最新日期和id从同一数据帧。 2从另一个基于日期和id的数据帧

df
id  date        name    location    type
11  08-05-2019  aim     ind         ss
12  08-05-2019  paul    uk          ee
11  08-04-2019  aim     ee
13  08-05-2019  tera    uk          jj
13  08-01-2019  tera                kk
15  08-09-2019          usa         ii
15  08-05-2019          uk          ii
13  08-05-2019  tera    uk

基于id和最新日期从同一数据帧填充nan的预期输出

df1
id  date        name    location    type
11  08-05-2019  aim     ind         ss
12  08-05-2019  paul    uk          ee
11  08-04-2019  aim     ind         ss
13  08-05-2019  tera    uk          jj
13  08-01-2019  tera    uk          kk
15  08-09-2019          usa         ii
15  08-05-2019          uk          ii
13  08-05-2019  tera    uk          jj

在df1中,我只需要根据date和id列替换数据帧y中nan的值。你知道吗

y
id  date        name    location    type    rev
11  08-05-2019  aim     ind         ss      yes
12  08-05-2019  paul    uk          ee      no
11  08-04-2019  aim     ind         ee      yes
13  08-05-2019  tera    uk          jj      yes
13  08-01-2019  tera    uk          kk      yes
15  08-09-2019  sam     usa         ii      no
15  08-05-2019  jim     uk          ii      no
13  08-05-2019  tera    uk          kk      no
14  09-05-2019  tiya    uk          kk      yes
15  10-05-2019  tiya    ind         kk      yes

我尝试了第二个选项的代码,但没有完全工作。你知道吗

y.set_index(['id','date']).combine_first(df1.set_index(['id','date'])).reset_index()

以及

df, y = df.set_index('id','date'), y.set_index('id','date')
df.update(y)
df.reset_index(inplace=True)

但是得到多索引错误

我无法从df获得df1,所以直接尝试在y的帮助下更新df

最终预期输出为

id  date        name    location    type
11  08-05-2019  aim     ind         ss
12  08-05-2019  paul    uk          ee
11  08-04-2019  aim     ind         ee
13  08-05-2019  tera    uk          jj
13  08-01-2019  tera    uk          kk
15  08-09-2019  sam     usa         ii
15  08-05-2019  jim     uk          ii
13  08-05-2019  tera    uk          kk

Tags: 数据iddfdateindexsseeyes
1条回答
网友
1楼 · 发布于 2024-05-19 11:03:00

您刚刚得到了数据帧名称的相反顺序。以下方法应该有效

df1.set_index(['id','date']).combine_first(y[df1.columns].set_index(['id','date'])).reset_index()

相关问题 更多 >

    热门问题