【问题标题】:How to drop rows from one dataframe if there is no match in another dataframe based on common column?如果基于公共列的另一个数据框中没有匹配项,如何从一个数据框中删除行?
【发布时间】:2021-11-13 19:24:42
【问题描述】:

我浏览了论坛,但仍然无法弄清楚。

如果第一个数据帧中不存在行,我会尝试从第二个数据帧中删除它们。该条件基于 r_id 列,其中该行中的 id 需要存在于第一个数据帧中。

我试过这个:

df2 = pd.merge(df2, df1[['r_id']] , on=['r_id'], how='inner')

但是,df2 中仍有一些行 (r_ids) 不在 df1 中。

df1 看起来像这样:

r_id  tmp  meds hr
4968    2   0   0
4968    2   0   0
4968    2   0   0
4968    2   0   0
4968    2   0   0


df2 看起来像这样:

r_id    date
4968    02/08/2020
4968    02/08/2020
4968    02/08/2020
4968    31/10/2020
4968    31/10/2020
4968    31/10/2020
3245    20/12/2020
3245    20/12/2020

然而,df2 应该是这样的:

r_id    date
4968    02/08/2020
4968    02/08/2020
4968    02/08/2020
4968    31/10/2020
4968    31/10/2020
4968    31/10/2020

知道该怎么做吗?

【问题讨论】:

  • 两个 r_id 列中的 dtypes 是否相同?

标签: python pandas dataframe time-series


【解决方案1】:
data1 = {
'r_id': ['4968', '4968', '4968', '4968', '4968'],
'tmp': [2, 2, 2, 2, 2],
'meds': [0, 0, 0, 0, 0],
'hr': [0, 0, 0, 0, 0],
}

data2 = {
'r_id': ['4968', '4968', '4968', '4968', '4968', '4968', '3245', '3245'],
'date': ['02/08/2020', '02/08/2020', '02/08/2020', '31/10/2020', '31/10/2020', '31/10/2020', '20/12/2020', '20/12/2020'],
}

df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
df2_copy = df2.copy()

df2 = [df2.r_id.isin(set(df1.r_id))]

# Check the difference between the new df2 and the original one.
print(df2_copy)
print(df2)

【讨论】:

    【解决方案2】:

    首先,确保您的密钥是正确的数据类型。

    df1.r_id = df1.r_id.astype(str)
    df2.r_id = df2.r_id.astype(str)
    

    然后您使用唯一 ID 过滤您的数据框。

    df2 = df2[df2.r_id.isin(df1.r_id.unique().tolist())]
    

    【讨论】:

    • @TSRAI df2.r_id.dtype 给你什么?还有df1.r_id.dtype?
    • @U12-Forward 都是 int64 dtypes
    • @TSRAI 如果你试试df2.loc[df2['r_id'].isin(df1['r_id'])]
    【解决方案3】:

    你可以试试

    df2 = df2[df2.r_id.isin(df1.r_id),]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 2021-12-12
      相关资源
      最近更新 更多