【问题标题】:Filling Nulls from other Dataframe从其他数据框填充空值
【发布时间】:2020-07-13 20:13:41
【问题描述】:

我有两个数据框,df1 和 df2。考虑到唯一标识符(id),我想根据 df1 中的相应条目填充 df2 中的空值。下面是代码:

import pandas as pd
import numpy as np
df1 = pd.DataFrame({"id": [3,4,5,6,7,8,9],
                     "col1": ['mike', 'matt', 'mertha', 'peter', 'tabby', 'carl', 'brian'],
                     "col2": ['645-345', '645-333', '324-543', '123-432', '563-654', '324-123', '902-342'],
                     "col3": ['cat', 'cat','dog', 'none', 't-rex', 'goat', 'snake']})
df2 = pd.DataFrame({"id": [6, 6, 7, 7, 7, 8, 8, 9],
                    "col1": ['peter', 'peter', np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
                    "col2": ['324-123','324-123', '902-342', '902-332', '902-123', '556-786', '113-786', '901-345'],
                    "col3": ['none', 'none', np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]})

为简洁起见,当我在这个网站上尝试所有东西时,我并不是在开玩笑,但我似乎无法找到答案。任何帮助将不胜感激!

已编辑:预期输出

我只想填写col1col3 np.nan 值。 None 只是另一种选择。我的预期输出如下:

df_merged = pd.DataFrame({"id": [6, 6, 7, 7, 7, 8, 8, 9],
                    "col1": ['peter', 'peter', 'tabby','tabby', 'tabby',  'carl','carl','brian'],
                    "col2": ['324-123','324-123', '902-342', '902-332', '902-123', '556-786', '113-786', '901-345'],
                    "col3": ['none', 'none', 't-rex', 't-rex', 't-rex', 'goat', 'goat', 'snake']})

【问题讨论】:

  • 您也想替换字符串'none' 吗?另外,您的预期输出是什么?
  • 我将用预期的输出编辑帖子,抱歉。

标签: python pandas dataframe merge


【解决方案1】:

如果id 是两个数据帧中的索引,那么 Erfan 的注释应该有效。否则:

(df2.set_index('id')
    .fillna(df1.set_index('id'))
    .reset_index()
)

输出:

   id   col1     col2   col3
0   6  peter  324-123   none
1   6  peter  324-123   none
2   7  tabby  902-342  t-rex
3   7  tabby  902-332  t-rex
4   7  tabby  902-123  t-rex
5   8   carl  556-786   goat
6   8   carl  113-786   goat
7   9  brian  901-345  snake

【讨论】:

  • 我喜欢这个,如果在更大的数据集上需要它,我会看看并回复。最终,如果可能的话,我想避免篡改索引。这是生产管道的一部分,我的老板不建议弄乱索引。
  • 我可以吻你!无论出于何种原因,这对我来说都是一件困难的事情。我应该退后一步,让我的大脑处理它。谢谢你。请问这个,管道数据对set_index有影响吗?
  • 否,set_index 和 reset_index 都默认创建新的dataFrame。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 2023-02-04
相关资源
最近更新 更多