【问题标题】:Concatenating two dfs in Pandas在 Pandas 中连接两个 dfs
【发布时间】:2019-07-22 01:07:53
【问题描述】:

我想知道是否有一种方法可以验证一个 df 中与另一个 df 连接的值是否存在于两个 dfs 或另一个 df 中,然后再将它们堆叠在一起??

我有两个 dfs

df = pd.concat([df1, df2])
df = df.sort_values(by=['id', 'timestamp']).reset_index(drop=True)
df

   id  timestamp
0   1 1959-06-01
1   1 2019-01-01
2   1 2019-01-02
3   2 1989-12-01
4   2 2019-01-15
5   3 1999-01-25
6   3 2019-01-17
7   3 2019-02-01
8   3 2019-02-03

在连接类似于合并之前,有没有办法验证 df1 中的 I.D 是否存在于 df2 中?我不需要合并,而是将 dfs 相互连接起来。

一个 df 有多个 id 和时间戳,另一个只有一个 ID,我想确保只有两个都存在的 ID 出现在生成的连接 df 中

谢谢!

【问题讨论】:

  • 您要检查一列还​​是整行?

标签: python python-3.x pandas merge concatenation


【解决方案1】:

这就是你要找的吗? 附上示例代码。

df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],'B': ['B0', 'B1', 'B2']})
new = df.set_index('key').join(other.set_index('key'))
new.dropna(axis=0, how='any', thresh=None, subset=None, inplace=True)
print(new)

或者

import pandas as pd 
df = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3', 'K4', 'K5'],'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5']})
other = pd.DataFrame({'key': ['K0', 'K1', 'K2'],'A': ['A0', 'A1', 'A2']})
new = pd.merge(df , other , how = 'inner')
print(new)

这对你有帮助吗?

【讨论】:

    【解决方案2】:

    您可以使用df.isin请尝试..

    【讨论】:

      【解决方案3】:

      检查整行

      df3=pd.concat([df1,df2[~df2.isin(df1)]],ignore_index=True).dropna()
      

      检查一列

      df3=pd.concat([df1,df2[~df2['col_name'].isin(df1['col_name'])]],ignore_index=True).dropna()
      

      【讨论】:

        【解决方案4】:

        您可以在此处执行的一种解决方法是创建一个虚拟列:

        df1["df"] = 1
        df2["df"] = 2
        df = pd.concat([df1, df2])
        

        这样您就可以看到每一行的派生位置。

        【讨论】:

          猜你喜欢
          • 2017-01-20
          • 2020-09-02
          • 2018-05-10
          • 1970-01-01
          • 2019-03-27
          • 1970-01-01
          • 2021-10-09
          • 1970-01-01
          • 2019-11-28
          相关资源
          最近更新 更多