Python Pandas:使用基于不同列中的分类值的计算来创建新列

时间:2018-08-24 16:10:05

标签: python pandas conditional where calculation

我有以下示例数据框:

id  category        time
43  S               8
22  I               10
15  T               350
18  L               46

我要应用以下逻辑:

1)如果类别值等于“ T”,则创建一个名为“ time_2”的新列,其中“时间”值除以24。

2)如果类别值等于“ L”,则创建一个名为“ time_2”的新列,其中“时间”值除以3.5。

3)否则从类别S或I中获取现有的“时间”值

下面是我想要的输出表:

    id  category        time    time_2
    43  S               8       8
    22  I               10      10
    15  T               350     14.58333333
    18  L               46      13.14285714

我尝试使用pd.np.where使以上内容正常工作,但对语法感到困惑。

2 个答案:

答案 0 :(得分:2)

您可以将map用于规则

In [1066]: df['time_2'] = df.time / df.category.map({'T': 24, 'L': 3.5}).fillna(1)

In [1067]: df
Out[1067]:
   id category  time     time_2
0  43        S     8   8.000000
1  22        I    10  10.000000
2  15        T   350  14.583333
3  18        L    46  13.142857

答案 1 :(得分:1)

您可以使用np.select。这是嵌套np.where逻辑的不错选择。

conditions = [df['category'] == 'T', df['category'] == 'L']
values = [df['time'] / 24, df['time'] / 3.5]

df['time_2'] = np.select(conditions, values, df['time'])

print(df)

   id category  time     time_2
0  43        S     8   8.000000
1  22        I    10  10.000000
2  15        T   350  14.583333
3  18        L    46  13.142857
相关问题