根据其他列的值创建新列

时间:2018-01-21 17:56:13

标签: python pandas

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

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

4 个答案:

答案 0 :(得分:2)

console.log | or使用带有链式条件的numpy.where

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

dictionarydf['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
{{1}}

答案 1 :(得分:1)

尝试使用.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')

答案 2 :(得分:0)

使用map

df['High Value Indicator'] =((df.Value_1 > 1000) | (df.Value_2 > 15000)).map({True:'Y',False:'N'})
df
Out[849]: 
   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

答案 3 :(得分:0)

您也可以使用apply:

df['High Value Indicator'] = (
     df.apply(lambda x: 'Y' if (x.Value_1>1000 or x.Value_2>15000) else 'N', axis=1)
     )
相关问题