【问题标题】:how to create new column based on multiple columns with a function如何使用函数基于多列创建新列
【发布时间】:2016-07-09 16:28:49
【问题描述】:

这个问题是我关于linear interpolation between two data points的问题的后续

我从中构建了以下功能:

def inter(colA, colB):
   s = pd.Series([colA, np.nan, colB], index= [95, 100, 102.5])
   s = s.interpolate(method='index')
   return s.iloc[1]

现在我有一个如下所示的数据框:

           on95   on102.5   on105
Index
  1         5       17        20
  2         7       15        25
  3         6       16        23

我想创建一个新列df['new'],它使用函数inter,输入为on95on102.5

我试过这样:

df['new'] = inter(df['on95'],df['on102.5'])

但这导致了 NaN。

我也尝试了apply(inter),但没有找到一种方法让它在没有错误消息的情况下工作。

任何提示我如何解决这个问题?

【问题讨论】:

    标签: python function pandas vectorization


    【解决方案1】:

    您需要使用np.vectorize 对自定义函数进行矢量化,因为函数参数被接受为熊猫系列:

    inter = np.vectorize(inter)
    df['new'] = inter(df['on95'],df['on102.5'])
    df
    
                on95    on102.5 on105         new
    #Index              
    #   1          5        17    20    13.000000
    #   2          7        15    25    12.333333
    #   3          6        16    23    12.666667
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多