Python 基于其他列的值创建新列
我想创建一个“High Value Indicator”列,根据两个不同的值列显示“Y”或“N”。当值_1>1000或值_2>15000时,我希望新列具有“Y”。下面是表格,所需输出将包括基于或条件的指示器列Python 基于其他列的值创建新列,python,pandas,Python,Pandas,我想创建一个“High Value Indicator”列,根据两个不同的值列显示“Y”或“N”。当值_1>1000或值_2>15000时,我希望新列具有“Y”。下面是表格,所需输出将包括基于或条件的指示器列 ID Value_1 Value_2 1 100 2500 2 250 6250 3 625 15625 4 1500 37500 5 3750 93750 尝试使用.
ID Value_1 Value_2
1 100 2500
2 250 6250
3 625 15625
4 1500 37500
5 3750 93750
尝试使用.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')
通过或的与链接条件一起使用:
df['High Value Indicator'] = np.where((df.Value_1 > 1000) | (df.Value_2 > 15000), 'Y', 'N')
或通过字典:
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)
使用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
您还可以使用apply:
df['High Value Indicator'] = (
df.apply(lambda x: 'Y' if (x.Value_1>1000 or x.Value_2>15000) else 'N', axis=1)
)
df['High Value Indicator'] = (
df.apply(lambda x: 'Y' if (x.Value_1>1000 or x.Value_2>15000) else 'N', axis=1)
)