【问题标题】:How to fill only missing values in one dataframe column with values from another dataframe in python?如何用python中另一个数据框的值仅填充一个数据框列中的缺失值?
【发布时间】:2021-03-25 03:14:02
【问题描述】:

我有 2 个数据框,每个数据框都有多个列。两个数据框都将“SendID”和“SendDateTime”列为唯一相同的列。两个数据框都完全填写了“SendID”。 Df1 缺少 30,000 个“SendDateTime”。 Df2 已填写所有“SendID”和“SendDateTime”。我想通过使用“SendID”从 df2 获取 df1 中缺少的“SendDateTime”。两个数据框都有多个不匹配的列。

df1(7 列)

SendID   SendDateTime             Link
12345    10/12/2019  8:00:00 AM   Text Box
12345    10/12/2019  8:00:00 AM   View Browser
98765                             News
98765                             Social
45678    12/24/2019  11:00:00 AM  Shop
45678    12/24/2019  11:00:00 AM  Button

df2(8 列)

SendID   SendDateTime             Subject
12345    10/12/2019  8:00:00 AM   Hello
98765    11/19/2019  9:30:00 AM   Welcome
45678    12/24/2019  11:00:00 AM  Please Read

df1 中的所需输出(相同的 7 列)因此所有缺少的“SendDateTime”都使用 df2 中的“SendID”填充:

SendID   SendDateTime             Link
12345    10/12/2019  8:00:00 AM   Text Box
12345    10/12/2019  8:00:00 AM   View Browser
98765    11/19/2019  9:30:00 AM   News
98765    11/19/2019  9:30:00 AM   Social
45678    12/24/2019  11:00:00 AM  Shop
45678    12/24/2019  11:00:00 AM  Button

我试过了:

miss = df1[df1['SendDateTime'].isnull()]
nonmiss = df1[df1['SendDateTime'].notnull()]
miss = miss.merge(df2, how='left', on='SendID')
df1 = nonmiss.append(miss)

我也试过了:

df1.update(df2)
print(df1)

我怎样才能正确地做到这一点?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以从 df2 获取不同的 id/times,然后在删除时间列后将它们合并到 df1。

    df2_t = df2[['SendID','SendDateTime']].drop_duplicates()
    df1.drop(columns='SendDateTime').merge(df2_t, on='SendID')
    

    输出

       SendID          Link             SendDateTime
    0   12345      Text Box   10/12/2019  8:00:00 AM
    1   12345  View Browser   10/12/2019  8:00:00 AM
    2   98765          News   11/19/2019  9:30:00 AM
    3   98765        Social   11/19/2019  9:30:00 AM
    4   45678          Shop  12/24/2019  11:00:00 AM
    5   45678        Button  12/24/2019  11:00:00 AM
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2018-07-25
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多