【问题标题】:Vertical Merging of Pandas Series熊猫系列纵向合并
【发布时间】:2018-01-08 16:53:45
【问题描述】:

我目前有两个共享一个公共列的数据框,如下所示:

df1 = 
    Text    Val
    "This"     1
    "That"     2
    "Is"       3
    "Not"      ''
    "Working"  ''

df2 = 
    Text    Val
    "This"     ''
    "That"     ''
    "Is"       ''
    "Not"      4
    "Working"  5

我想通过以下方式合并两个数据框:

merged_df = 
    Text    Val
    "This"     1
    "That"     2
    "Is"       3
    "Not"      4
    "Working"  5

本质上,两个数据框 df1 和 df2 都共享一个共同的“文本”列。所有的值都是相似的。但是,在 df1 中,没有对应于“Not”和“Working”的行的值,但这些在 df2 中可用。

一种方法如何将这些堆叠在一起以得出merged_df?

与我的实际数据相比,这些示例微不足道,但希望这会有所帮助

【问题讨论】:

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


    【解决方案1】:

    您可以使用combine_firstset_index 来对齐数据并替换为NaNs(如有必要):

    df1['Val'] = df1['Val'].replace("''",np.nan)
    df2['Val'] = df2['Val'].replace("''",np.nan)
    
    df = df1.set_index('Text').combine_first(df2.set_index('Text')).reset_index()
    print (df)
          Text Val
    0     This   1
    1     That   2
    2       Is   3
    3      Not   4
    4  Working   5
    

    【讨论】:

    • 谢谢@jezrael!我不知道 pandas 中的 combine_first 方法。
    • 很高兴能帮上忙,美好的一天!
    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 2021-01-08
    • 2019-03-07
    • 2015-05-09
    • 2014-09-15
    • 2019-09-27
    相关资源
    最近更新 更多