繁体   English   中英

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

[英]Python Pandas: Create New Column With Calculations Based on Categorical Values in A Different Column

我有以下示例数据框:

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使上面的工作,但对语法感到困惑。

您可以将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

您可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM