【问题标题】:Merge a dataframe only when the column values are identical仅当列值相同时才合并数据框
【发布时间】:2021-02-18 03:17:26
【问题描述】:

我有两个数据框 dfdf_copy。我想从df_copy 复制数据,但前提是数据也相同。我该怎么做?

import pandas as pd

d = {'Nameid': [100, 200, 300, 100]
     , 'Name': ['Max', 'Michael', 'Susan', 'Max']
     , 'Projectid': [100, 200, 200, 100]}

df = pd.DataFrame(data=d)
display(df.head(5))

df['nameid_index'] = df['Nameid'].astype('category').cat.codes
df['projectid_index'] = df['Projectid'].astype('category').cat.codes
display(df.head(5))

df_copy = df.copy()

df.drop(['Nameid', 'Name', 'Projectid'], axis=1, inplace=True)
df = df.drop([1, 3])
display(df.head(5))

df

df_copy

我想要什么


我看了Pandas Merging 101

df.merge(df_copy, on=['nameid_index', 'projectid_index'])

但我得到了这个结果

同一行有两次,我只想要一次。

【问题讨论】:

  • 那么需要df.drop_duplicates(['nameid_index', 'projectid_index']).merge(df_copy, on=['nameid_index', 'projectid_index']) 吗?
  • @jezrael 非常感谢您!不知道我结合了这个。谢谢。

标签: python pandas dataframe


【解决方案1】:

首先使用DataFrame.drop_duplicates

df1 = (df.drop_duplicates(['nameid_index', 'projectid_index'])
         .merge(df_copy, on=['nameid_index', 'projectid_index']))

如果需要通过DataFrames中两个列名的交集进行合并,则应删除on参数:

df1 = df.drop_duplicates(['nameid_index', 'projectid_index']).merge(df_copy)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2022-01-10
    • 2021-12-17
    相关资源
    最近更新 更多