【问题标题】:How to merge two different variables with differente indexes?如何合并具有不同索引的两个不同变量?
【发布时间】:2020-07-12 05:59:47
【问题描述】:

我正在处理一个大型数据集,我不得不清理一些行,所以现在没有遵循索引,因为有些索引丢失了。现在我有:

        A
2       2
5       4
7       5
8       6
17      6
21      8

无论 A 列是什么意思,我都必须对其进行处理、拆分和转换。所以,最后,我有两个由该操作产生的变量(A_case1,A_case2),其中:

print(A_case1)

2    4
7    2
17   3
21   2

print(A_case2)

5   2
8   1

但现在我想合并这两个变量并加入原始数据框。所以我希望最终的结果是:

        A   A_case1_Case2
2       2   4
5       4   2
7       5   2
8       6   1
17      6   3
21      8   2

我已经尝试过 pd.concat 但无法加入数据框。谁能帮帮我?

【问题讨论】:

    标签: python pandas indexing merge concatenation


    【解决方案1】:

    首先将新的数据框A_case1A_case2合并到原始数据框(df)中:

    merged = df.merge(A_case1, left_index=True, right_index=True, how='left').merge(A_case2, left_index=True, right_index=True, how='left')
    

    然后通过连接两个中间列A_case1A_case2 来创建新列A_case1_case2

    merged['A_case1_case2'] = merged[['A_case1', 'A_case2']].apply(lambda x: ''.join(x.dropna().astype(int).astype(str)), 1)
    

    最后删除中间列A_case1A_case2

    merged = merged.drop(['A_case1', 'A_case2'], 1)
    

    【讨论】:

    • 当我应用您编写的第一行代码时,它显示错误“无法将 DataFrame 与 类型的实例合并”
    • 您的数据似乎不是一个数据框,而是一个系列。看看this question 来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2022-01-16
    • 2020-01-23
    相关资源
    最近更新 更多