【问题标题】:Apply a binary function to two Pandas Series将二元函数应用于两个 Pandas 系列
【发布时间】:2021-06-03 15:19:43
【问题描述】:

binary function 应用于两个Pandas Series elementwise 的推荐方法是什么,当它们具有相同的索引时将值配对在一起,并在其中一个系列缺少值时提供填充值?

例如,输入系列slsr 应该产生输出系列so

sl = Pandas Series
index,value
a,1
b,4
c,5
e,7

sr = Pandas Series
index,value
a,2
b,3
d,6
e,7

so = binary_func(sl, sr, fill_value=0)
index,value
a,binary_func(1,2)
b,binary_func(4,3)
c,binary_func(5,0)
d,binary_func(0,6)
e,binary_func(7,7)

【问题讨论】:

    标签: python python-3.x pandas series


    【解决方案1】:

    您可以使用带有fillna(0) 的DataFrame,然后在行上使用apply 您的binary_func

    import pandas as pd
    
    sl = pd.Series([1, 4, 5, 7], index=list('abce'))
    sr = pd.Series([2, 3, 6, 7], index=list('abde'))
    
    df = pd.DataFrame({ 'sl': sl, 'sr': sr }).fillna(0)
    
    sl sr
    a 1.0 2.0
    b 4.0 3.0
    c 5.0 0.0
    d 0.0 6.0
    e 7.0 7.0
    so = df.apply(lambda row: binary_func(row[0], row[1]), axis=1)
    

    【讨论】:

    • 这对我来说实际上运行得很慢(在大型数据集上)。我想知道是否有更有效的解决方案。不过仍然是一个不错的答案。
    • 代替df.apply 步骤,尝试像binary_func_vec = np.vectorize(binary_func) 这样对函数进行矢量化,然后使用像binary_func_vec(df.s1.values, df.s2.values) 这样的numpy 数组调用它。
    • 谢谢!如果这行得通,它应该是一个单独的答案。比较这两种方法的速度会很有价值!
    猜你喜欢
    • 1970-01-01
    • 2016-03-20
    • 2021-02-03
    • 2012-10-31
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多