【问题标题】:How to join two tables with same column names but with different data using pandas?如何使用熊猫连接两个具有相同列名但具有不同数据的表?
【发布时间】:2021-12-05 05:41:24
【问题描述】:

假设

df1,

col1 | col2 | col3 | col4 |
A    |  131 | 666  | 777  |
B    |  123 | 345  | 435  |
C    | 1424 | 3214 | 2314 |

df2,

col1 | col2 | col3 | col4 |
A    |  10  | 1    | 0    |
B    |  20  | 14   | 68   |
C    |  23  | 43   | 4    |

我想要达到的最终df,

col1 | col2           | col3         | col4      |
A    |  131 (10%)     | 666 (1%)     | 777       |
B    |  123 (20%)     | 345 (14%)    | 435 (68%) |
C    |  1424 (23%)    | 3214 (43%)   | 2314 (4%) | 

附:这些数字只是随机的

【问题讨论】:

    标签: python pandas dataframe join


    【解决方案1】:

    您可以将DataFrames转换为字符串,将0替换为缺失值,添加( %),因此对于缺失值不添加最后添加DataFrame

    df = ((df1.set_index('col1').astype(str) + 
          (' (' + df2.set_index('col1').astype(str).replace('0', np.nan) + '%)').fillna(''))
          .reset_index())
    print (df)
      col1        col2        col3       col4
    0    A   131 (10%)    666 (1%)        777
    1    B   123 (20%)   345 (14%)  435 (68%)
    2    C  1424 (23%)  3214 (43%)  2314 (4%)
    

    另一个想法是DataFrame.mask 的测试值:

    df11 = df1.set_index('col1').astype(str)
    df22 = df2.set_index('col1').astype(str)
    
    df = (df11 + (' (' + df22 + '%)').mask(df22.eq('0'), '')).reset_index()
          
    print (df)
      col1        col2        col3       col4
    0    A   131 (10%)    666 (1%)        777
    1    B   123 (20%)   345 (14%)  435 (68%)
    2    C  1424 (23%)  3214 (43%)  2314 (4%)
    

    【讨论】:

      【解决方案2】:

      applymap:

      >>> (df1.set_index('col1').astype(str).add(df2.set_index('col1')
                            .applymap(lambda x: f' ({x}%)' if x else ''))
                            .reset_index())
        col1        col2        col3       col4
      0    A   131 (10%)    666 (1%)        777
      1    B   123 (20%)   345 (14%)  435 (68%)
      2    C  1424 (23%)  3214 (43%)  2314 (4%)
      >>> 
      

      如果不是0,此代码会将df2 中的字符串添加一个百分号。它使用set_index 合并到同一个col1 上,并使用applymap 对其进行格式化。

      【讨论】:

      • 这不会产生预期的输出:OP 想要 777 但您的代码会产生 0 (777%)
      • @MuhammadHassan 为什么...它对我有用...
      • 对不起,我把他的df颠倒了,我用OP的df1作为df2
      • @MuhammadHassan 是的
      猜你喜欢
      • 2021-07-29
      • 1970-01-01
      • 2016-08-12
      • 2016-08-23
      • 2020-11-27
      • 2017-09-20
      • 2021-11-16
      • 2013-07-24
      • 1970-01-01
      相关资源
      最近更新 更多