【问题标题】:Dataframe Index row comparison and removalDataframe 索引行比较和删除
【发布时间】:2021-01-11 13:37:43
【问题描述】:

早安,

我需要一些建议,我有两个数据框。一个包含数百行,另一个包含六个。两个帧的时间戳都被索引。我想将 df1 中的索引值与 df2 进行比较,并仅保留与 df2 中的时间戳匹配的行。

df1
Date-Time                A    B    C    D
2012-01-11 7:10:05:00    0    1    2    3
2012-01-11 7:14:05:00    0    1    2    3
2012-01-11 7:16:05:00    0    1    2    3
2012-01-11 7:25:05:00    0    1    2    3
2012-01-11 7:31:05:00    0    1    2    3

df2
Date-Time                A    B    C    D
2012-01-11 7:10:05:00    6    8    1.5  6.8
2012-01-11 7:25:05:00    0    11   4    3.3
2012-01-11 7:31:05:00    0    44   2.2  3.3

所以只有第 0、3 和 4 行应该保留在 d1 中

【问题讨论】:

  • Date-Time 是索引还是列?

标签: python pandas dataframe isin


【解决方案1】:

确保您的“日期时间”列在两者中都是index(您可以通过set_index() 获取它,然后选择1:

1) 使用isin

df1_new = df1[df1.index.isin(df2.index)]

2) 使用loc

df1_new = df1.loc[df2.index, :]

【讨论】:

    【解决方案2】:

    将索引更改为列,然后按照以下链接中的说明将其更改回索引

    Compare two pandas dataframe with different size

    【讨论】:

      【解决方案3】:

      如果Date-Time 是一个列,试试这个: df1 = df1[ df1['Date-Time'] == df2['Date-Time'] ]

      您也可以通过合并数据框来做到这一点:

      df1 = pd.merge(df2['Date-Time'], df1, on='Date-Time', how='left')
      

      【讨论】:

        【解决方案4】:

        应该这样做 df1.loc[df1.index.isin(df2.index)]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-04
          • 1970-01-01
          • 2017-03-25
          • 2019-01-25
          • 2014-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多