【问题标题】:Apply function for two dataframes in pandas为熊猫中的两个数据框应用函数
【发布时间】:2017-06-09 19:14:01
【问题描述】:

我有两个数据框。

df0

    a    b 
c  0.3  0.6
d  0.4  NaN    

df1

   a  b
c  3  2
d  0  4

我有一个自定义函数:

def concat(d0,d1):
    if d0 is not None and d1 is not None:
        return '%s,%s' % (d0, d1)
    return None

我期望的结果:

     a      b
  c  0.3,3  0.6,2
  d  0.4,0  NaN

如何将函数应用于这两个数据框?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这里有一个解决方案。 这个想法是首先将您的数据框减少到一个平面的值列表。这允许您使用zip 循环两个数据帧的值并应用您的函数。 最后,您使用 numpy reshape 回到原始形状

    new_vals = [concat(d0,d1) for d0, d1 in zip(df1.values.flat, df2.values.flat)]
    result = pd.DataFrame(np.reshape(new_vals, (2, 2)), index = ['c', 'd'], columns = ['a', 'b'])
    

    【讨论】:

      【解决方案2】:

      如果你是你的特定应用,你可以这样做:

      #Concatenate the two as String
      df = df0.astype(str) + "," +df1.astype(str)
      #Remove the nan
      df = df.applymap(lambda x: x if 'nan' not in x else np.nan)
      

      在性能方面你会比使用 apply 更好

      输出

          a        b
      c   0.3,3   0.6,2
      d   0.4,0    NaN
      

      【讨论】:

        【解决方案3】:

        addapplymapmask 一起使用:

        df = df0.astype(str).add(',').add(df1.astype(str))
        df = df.mask(df.applymap(lambda x: 'nan' in x))
        print (df)
               a      b
        c  0.3,3  0.6,2
        d  0.4,0    NaN
        

        另一种解决方案是最后用mask替换NaN,默认情况下Trues被替换为NaN

        df = df0.astype(str).add(',').add(df1.astype(str))
        m = df0.isnull() | df1.isnull() 
        print (m)
               a      b
        c  False  False
        d  False   True
        
        df = df.mask(m)
        print (df)
               a      b
        c  0.3,3  0.6,2
        d  0.4,0    NaN
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-10
          • 2021-12-30
          • 2014-07-04
          • 2015-08-29
          • 2018-11-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多