【问题标题】:Column wise concatenation of two dataframes两个数据帧的按列连接
【发布时间】:2023-04-02 00:17:01
【问题描述】:

我是 Python 和 Pandas 模块的初学者。我正在处理一个统计问题,我想合并两个具有特定样式的数据框。

这是我的第一个平均值数据框:

- 5.006 3.418   1.464   0.244
 - 5.936    2.770   4.260   1.326
 - 6.588    2.974   5.552   2.026

然后是标准值的第二个数据帧:

 - 0.352490 0.381024    0.173511    0.107210
 - 0.516171 0.313798    0.469911    0.197753
 - 0.635880 0.322497    0.551895    0.274650

那么有什么方法可以合并两个数据帧,使最终输出看起来像“mean”±“std”?比如“5.006±0.352490”?

谢谢!

【问题讨论】:

    标签: python string pandas dataframe concat


    【解决方案1】:

    你需要连接两个df,需要相同的索引和列名:

    df1.astype(str) + ' ± ' + df2.astype(str)
    

    另一种解决方案:

    df1.astype(str).add(' ± ').add(df2.astype(str))
    

    df = df1.astype(str) + ' ± ' + df2.astype(str)
    print (df)
                        0                 1                 2                 3
    0   -5.006 ± -0.35249  3.418 ± 0.381024  1.464 ± 0.173511   0.244 ± 0.10721
    1  -5.936 ± -0.516171   2.77 ± 0.313798   4.26 ± 0.469911  1.326 ± 0.197753
    2   -6.588 ± -0.63588  2.974 ± 0.322497  5.552 ± 0.551895   2.026 ± 0.27465
    

    【讨论】:

      【解决方案2】:

      使用.astype 转换为字符串,然后一个简单的连接就足够了。

      out = df.astype(str) + ' ± ' +  df2.astype(str)
      print(out)
                        0                 1                 2                 3
      0   5.006 ± 0.35249  3.418 ± 0.381024  1.464 ± 0.173511   0.244 ± 0.10721
      1  5.936 ± 0.516171   2.77 ± 0.313798   4.26 ± 0.469911  1.326 ± 0.197753
      2   6.588 ± 0.63588  2.974 ± 0.322497  5.552 ± 0.551895   2.026 ± 0.27465
      

      只要您在两个数据帧中具有相同的索引和列,就可以很好地工作。如果没有,您可以将一个设置为另一个:

      df2.index = df.index
      df2.columns = df.columns
      out = df.astype(str) + ' ± ' +  df2.astype(str)
      

      详情:

      df    
             0      1      2      3
      0  5.006  3.418  1.464  0.244
      1  5.936  2.770  4.260  1.326
      2  6.588  2.974  5.552  2.026
      
      df2    
                0         1         2         3
      0  0.352490  0.381024  0.173511  0.107210
      1  0.516171  0.313798  0.469911  0.197753
      2  0.635880  0.322497  0.551895  0.274650
      

      【讨论】:

      猜你喜欢
      • 2022-08-14
      • 2021-10-15
      • 2017-11-02
      • 2016-09-16
      • 2020-09-02
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多