【问题标题】:How to get unique dataframe rows based on multiple keys如何根据多个键获取唯一的数据框行
【发布时间】:2020-11-23 20:50:06
【问题描述】:

我有一个名为“df1”的数据框:

Name Type Destination Data1 Data2
Bob   Car         NY   asdf  dsfg
Liz   Car         NY   asdf  dsfg

还有一个叫“df2”:

Name Type Destination Data1 Data2
Bob  Train         LA   asdf  dsfg
Liz   Car          NY   asdf  dsfg

我想根据 3 个值将它们组合在一起以形成一个“键”:名称、类型、目的地以结束:

Name Type Destination
Bob   Car         NY
Bob Train         LA
Liz   Car         NY

在没有重复的地方,添加了 Bob, Train, LA... 的行,因为它是唯一的条目。

到目前为止我有:

new_df = pd.concat([df1.Name, df2.Name]).drop_duplicates().sort_values(ascending=True).reset_index(drop=True)

但这仅在尝试基于单个键组合唯一列表时才有效。

【问题讨论】:

标签: python pandas dataframe merge concat


【解决方案1】:
  • 使用pandas.DataFrame.duplicated,它返回表示重复行的布尔系列。
    • 整行用于确定重复项。
    • 为所有重复的行返回True,因此要保留不重复的行,请使用~,即(NOT)。
  • 如果输出中只需要特定列,则必须使用.iloc 或df1[['Name', 'Type', 'Destination']] 指定它们,或者可以在使用concat 后删除它们。
import pandas as pd

data1 = {'Name': ['Bob', 'Liz'], 'Type': ['Car', 'Car'], 'Destination': ['NY', 'NY'], 'Data1': ['asdf', 'asdf'], 'Data2': ['dsfg', 'dsfg']}
data2 = {'Name': ['Bob', 'Liz'], 'Type': ['Train', 'Car'], 'Destination': ['LA', 'NY'], 'Data1': ['asdf', 'asdf'], 'Data2': ['dsfg', 'dsfg']}

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

# concat all the desired rows
dfc = pd.concat([df1.iloc[:, :3], df2.iloc[:, :3]])

# drop the duplicated row
dfc = dfc[~dfc.duplicated()]

# display(dfc)

  Name   Type Destination
0  Bob    Car          NY
1  Liz    Car          NY
0  Bob  Train          LA

选项 2

dfc = pd.concat([df1, df2]).drop_duplicates(subset=['Name', 'Type', 'Destination'])

# display(dfc)

  Name   Type Destination Data1 Data2
0  Bob    Car          NY  asdf  dsfg
1  Liz    Car          NY  asdf  dsfg
0  Bob  Train          LA  asdf  dsfg

【讨论】:

  • 糟糕,有道理。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 2021-12-29
  • 2018-11-02
相关资源
最近更新 更多