【问题标题】:Merge Columns in Pandas Dataframe合并 Pandas 数据框中的列
【发布时间】:2019-07-23 22:46:45
【问题描述】:

我有一个包含三列的数据框

Col1    Col2    Col3  Col4  Col 5
---------------------------------
Apple   None    192    abc   None
Banana  Banana  89     None  bcd
None    Cake    892    aaa   aaa

我想合并两列,即 Col1 和 Col2 以及 col1 和 col5 如果没有一列而另一列有值,则使用该值,如果两者都有值,则使用该值。
是否可以合并这样的列。

Col1    Col3     Col4
----------------------
Apple   192      abc
Banana  89       bcd
Cake    892      aaa

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用(如果 None 是字符串首先替换为 np.nan : df=df.replace('None',np.nan)):

    df_new=df.ffill().bfill()[['Col1','Col3']]
    print(df_new)
    
         Col1  Col3
    0   Apple   192
    1  Banana    89
    2  Banana   892
    

    基于更新:

    df.bfill(axis=1)[['Col1','Col3','Col4']]
    
         Col1 Col3 Col4
    0   Apple  192  abc
    1  Banana   89  bcd
    2    Cake  892  aaa
    

    【讨论】:

    • 有没有办法提到要合并的列,因为我有五个列,1,2,3,4,5 并且想要合并 1and2,4and 5 并且输出为 1,3,5 .
    • @Constantine1991 如果您可以在示例中添加一些额外的列,这将很有帮助。 :)
    • 更新问题
    • @Constantine1991 更新了答案,这行得通吗?
    【解决方案2】:

    创建您的映射 dict ,使用 first 执行 groupby

    d={'Col1':'Col1','Col2':'Col1','Col3':'Col3','Col4':'Col4','Col5':'Col4'}
    Yourdf=df.mask(df=='None').groupby(d,axis=1).first()
    Out[88]: 
         Col1  Col3 Col4
    0   Apple   192  abc
    1  Banana    89  bcd
    2    Cake   892  aaa
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 2021-06-21
      • 2018-09-04
      • 2022-11-13
      相关资源
      最近更新 更多