根据其他列的值创建新列

新手上路,请多包涵

我想创建一个“高价值指标”列,它根据两个不同的值列表示“Y”或“N”。当 Value_1 > 1,000 或 Value_2 > 15,000 时,我希望新列有一个“Y”。下面是表格,所需的输出将包括基于或条件的指示符列。

 ID   Value_1     Value_2
1    100         2500
2    250         6250
3    625         15625
4    1500        37500
5    3750        93750

原文由 Mike 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 245
2 个回答

尝试使用 .loc 和 .fillna

 df.loc[((df['Value_1'] > 1000)
       |(df['Value_2'] > 15000)), 'High_Value_Ind'] = 'Y'

df['High_Value_Ind'] = df['High_Value_Ind'].fillna('N')

原文由 Brian 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 numpy.where 与 --- 的链接条件 | or

 df['High Value Indicator'] = np.where((df.Value_1 > 1000) | (df.Value_2 > 15000), 'Y', 'N')

或者 map dictionary

 df['High Value Indicator'] = ((df.Value_1 > 1000) | (df.Value_2 > 15000))
                                 .map({True:'Y', False:'N'})

print (df)
   ID  Value_1  Value_2 High Value Indicator
0   1      100     2500                    N
1   2      250     6250                    N
2   3      625    15625                    Y
3   4     1500    37500                    Y
4   5     3750    93750                    Y

计时:

 df = pd.concat([df] * 10000, ignore_index=True)

 In [76]: %timeit df['High Value Indicator1'] = np.where((df.Value_1 > 1000) | (df.Value_2 > 15000), 'Y', 'N')
100 loops, best of 3: 4.03 ms per loop

In [77]: %timeit df['High Value Indicator2'] = ((df.Value_1 > 1000) | (df.Value_2 > 15000)).map({True:'Y', False:'N'})
100 loops, best of 3: 4.82 ms per loop

In [78]: %%timeit
    ...: df.loc[((df['Value_1'] > 1000)
    ...:        |(df['Value_2'] > 15000)), 'High_Value_Ind3'] = 'Y'
    ...:
    ...: df['High_Value_Ind3'] = df['High_Value_Ind3'].fillna('N')
    ...:
100 loops, best of 3: 5.28 ms per loop

In [79]: %timeit df['High Value Indicator'] = (df.apply(lambda x: 'Y' if (x.Value_1>1000 or x.Value_2>15000) else 'N', axis=1))
1 loop, best of 3: 1.72 s per loop

原文由 jezrael 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题