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" 的新列,其中 "time" 值除以 24。
2) 如果类别值等于 "L",则创建名为 "time_2" 的新列,其中 "time" 值除以 3.5。
3) 否则从类别 S 或 I
中获取现有 "time" 值
下面是我想要的输出 table:
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 来实现上述功能,但对语法感到困惑。
您可以使用 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
您可以使用 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
我有以下示例数据框:
id category time
43 S 8
22 I 10
15 T 350
18 L 46
我想应用以下逻辑:
1) 如果类别值等于 "T",则创建名为 "time_2" 的新列,其中 "time" 值除以 24。
2) 如果类别值等于 "L",则创建名为 "time_2" 的新列,其中 "time" 值除以 3.5。
3) 否则从类别 S 或 I
中获取现有 "time" 值下面是我想要的输出 table:
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 来实现上述功能,但对语法感到困惑。
您可以使用 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
您可以使用 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