如何在不拆分具有不同条件的数据帧的情况下执行公式

问题描述 投票:1回答:2

我有以下数据帧

import pandas as pd
d = {

    'ID':[1,2,3,4,5],
    'Price1':[5,9,4,3,9],
    'Price2':[9,10,13,14,18],
     'Type':['A','A','B','C','D'],


}
df = pd.DataFrame(data = d)
df

为了在没有条件的情况下应用公式,我使用以下代码

df = df.eval(
 'Price = (Price1*Price1)/2'
)
df

如何在不拆分具有不同条件的数据帧的情况下执行公式

需要一个名为Price_on_type的新列

每种类型的公式都不同

对于类型A,Price_on_type = Price1 + Price1的公式

对于B型,Price_on_type =(Price1 + Price1)/ 2的公式

对于类型C,Price_on_type = Price1的公式

对于类型D,Price_on_type = Price2的公式

预期产出:

import pandas as pd
d = {

    'ID':[1,2,3,4,5],
    'Price1':[5,9,4,3,9],
    'Price2':[9,10,13,14,18],
    'Price':[12.5,40.5, 8.0, 4.5, 40.5],
     'Price_on_type':[14,19,8.0,3,18],


}
df = pd.DataFrame(data = d)
df
pandas
2个回答
2
投票

你可以使用numpy.select

masks = [df['Type'] == 'A',
         df['Type'] == 'B',
         df['Type'] == 'C',
         df['Type'] == 'D']

vals = [df.eval('(Price1*Price1)'),
        df.eval('(Price1*Price1)/2'),
        df['Price1'],
        df['Price2']]

要么:

vals = [df['Price1'] + df['Price2'],
        (df['Price1'] + df['Price2']) / 2,
        df['Price1'],
        df['Price2']]

df['Price_on_type'] = np.select(masks, vals)
print (df)
   ID  Price1  Price2 Type  Price_on_type
0   1       5       9    A           14.0
1   2       9      10    A           19.0
2   3       4      13    B            8.5
3   4       3      14    C            3.0
4   5       9      18    D           18.0

1
投票

如果您的数据不是太大,请在apply上使用axis=1和自定义函数

def Prices(x):
    dict_sw = {
            'A': x.Price1 + x.Price2,
            'B': (x.Price1 + x.Price2)/2,
            'C': x.Price1,
            'D': x.Price2,
            }
    return dict_sw[x.Type]

In [239]: df['Price_on_type'] = df.apply(Prices, axis=1)

In [240]: df
Out[240]:
   ID  Price1  Price2 Type  Price_on_type
0   1       5       9    A           14.0
1   2       9      10    A           19.0
2   3       4      13    B            8.5
3   4       3      14    C            3.0
4   5       9      18    D           18.0

或使用技巧转换True1False0

df['Price_on_type'] = \
     (df.Type == 'A') * (df.Price1 + df.Price2) + \
     (df.Type == 'B') * (df.Price1 + df.Price2)/2 + \
     (df.Type == 'C') * df.Price1 + \
     (df.Type == 'D') * df.Price2

Out[308]:
   ID  Price1  Price2 Type  Price_on_type
0   1       5       9    A           14.0
1   2       9      10    A           19.0
2   3       4      13    B            8.5
3   4       3      14    C            3.0
4   5       9      18    D           18.0
© www.soinside.com 2019 - 2024. All rights reserved.