【问题标题】:Merging two pandas dataframes many-to-one多对一合并两个熊猫数据框
【发布时间】:2018-07-22 14:36:21
【问题描述】:

如何合并以下数据集:

df = A
date abc
1    a
1    b
1    c
2    d
2    dd
3    ee
3    df

df = B
date ZZZ
1    a
2    b
3    c

我想得到这样的东西:

date abc  ZZZ
1    a     a
1    b     a
1    c     a
2    d     b
2    dd    b
3    ee    c
3    df    c

我试过这段代码:

aa = pd.merge(A, B, left_on="date", right_on="date", how="left", validate="m:1")

但我有以下错误:

TypeError: merge() got an unexpected keyword argument 'validate'

我使用 (conda update pandas) 更新了我的 pandas,但仍然出现相同的错误

请告诉我这个问题。

【问题讨论】:

  • 你有什么版本的熊猫?即pd.__version__

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


【解决方案1】:

作为@DeepSpace mentioned,您可能需要升级您的熊猫。

要在早期版本中复制检查,您可以执行以下操作:

import pandas as pd

df1 = pd.DataFrame(index=['a', 'a', 'b', 'b', 'c'])
df2 = pd.DataFrame(index=['a', 'b', 'c'])

x = [i for i in df2.index if i in set(df1.index)]
len(x) == len(set(x))  # True


df1 = pd.DataFrame(index=['a', 'a', 'b', 'b', 'c'])
df2 = pd.DataFrame(index=['a', 'b', 'c', 'a'])

y = [i for i in df2.index if i in set(df1.index)]
len(y) == len(set(y))  # False

【讨论】:

    【解决方案2】:

    根据df.merge docsvalidate在0.21.0版本中添加。您使用的是旧版本,因此您应该更新您正在使用的 pandas 版本。

    【讨论】:

    • 是的,我更新了熊猫(conda update pandas),但我仍然面临同样的错误
    • @AlbertoAlvarez import pandas as pd ; print(pd.__version__) 如果您没有看到 0.21.0 或更新版本,这将不起作用。就这么简单。
    猜你喜欢
    • 2017-06-11
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2017-11-03
    相关资源
    最近更新 更多