【问题标题】:Concatenate two dataframes and drop duplicates in Pandas连接两个数据框并在 Pandas 中删除重复项
【发布时间】:2019-08-30 07:58:57
【问题描述】:

对于只有2019年份数据的df2

  type  year  value
0    a  2019     13
1    b  2019      5
2    c  2019      5
3    d  2019     20

df1 有多年数据:

  type  year  value
0    a  2015     12
1    a  2016      2
2    a  2019      3
3    b  2018     50
4    b  2019     10
5    c  2017      1
6    c  2016      5
7    c  2019      8

我需要将它们连接在一起,同时将2019 中的df2 值替换为df1 同年的值。

预期的结果是这样的:

  type  date  value
0    a  2015     12
1    a  2016      2
2    b  2018     50
3    c  2017      1
4    c  2016      5
5    a  2019     13
6    b  2019      5
7    c  2019      5
8    d  2019     20

来自pd.concat([df1, df2], ignore_index=True, sort =False) 的结果,其中一个type 显然在2019 年的year 中有多个value。我应该如何改进代码?谢谢。

   type  date  value
0     a  2019     13
1     b  2019      5
2     c  2019      5
3     d  2019     20
4     a  2015     12
5     a  2016      2
6     a  2019      3
7     b  2018     50
8     b  2019     10
9     c  2017      1
10    c  2016      5
11    c  2019      8

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    concat 之后添加DataFrame.drop_duplicates 以获得typedate 的最后一行。

    如果 typedate 对在两个 DataFrame 中都是唯一的,则解决方案有效。

    df = (pd.concat([df1, df2], ignore_index=True, sort =False)
            .drop_duplicates(['type','date'], keep='last'))
    

    【讨论】:

    • keep='last' 是否意味着将采用来自df1values 而不是df2?如果我写df = (pd.concat([df2, df1], ignore_index=True, sort =False).drop_duplicates(['type','date'], keep='last'))
    • @ahbon - 这意味着它获取连接行的最后一个值,所以如果存在则从df2 获取,如果不存在则从 df1 获取。
    • point - 在 pd.concat([df1, df2], ignore_index=True, sort =False) 之后 df1 的值是前 4 行,因此 keep='last' 保留原始值并且不会't 用新值更新..
    • I need to concatenate them together while replacing df2's values in 2019 with the values from df1's same year... 最好是更改名称:) +1
    • 你能把df = (pd.concat([df1, df2], ignore_index=True, sort =False) .drop_duplicates(['type','date', 'a', b, c], keep='last'))改成df = (pd.concat([df1, df2[df2.columns.intersection(df1.columns)], ignore_index=True, sort =False) .drop_duplicates(['type','date', 'a', b, c], keep='last')) - link
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 2020-12-21
    • 1970-01-01
    • 2011-11-18
    • 2020-08-11
    • 2020-11-09
    相关资源
    最近更新 更多