比較 COL1 和 COL2,如果 COL1 的值大于或等于 COL2,則突出顯示 COL1。COL1 包含不是數字的“測驗”。我需要跳過那一行并比較其余的。如何做到這一點?謝謝!

uj5u.com熱心網友回復:
如果將非數字替換為缺失值to_numeric,errors='coerce'您可以比較兩列Series.ge是否大于或等于,原始列不會被替換:
mask = pd.to_numeric(df['COL1'], errors='coerce').ge(df['COL2'])
df['new'] = np.where(mask, 'greater or equal', 'not greater or equal')
如果還需要非數字的不同輸出:
df = pd.DataFrame({'COL1':['text', 1,2],
'COL2':[1,2,0]})
s = pd.to_numeric(df['COL1'], errors='coerce')
mask1 = s.isna() & df['COL1'].notna()
mask2 = s.ge(df['COL2'])
df['new'] = np.select([mask1,mask2],
['non numeric','greater or equal'],
default='not greater or equal')
print (df)
COL1 COL2 new
0 text 1 non numeric
1 1 2 not greater or equal
2 2 0 greater or equal
對于突出顯示的完整性解決方案COL1是:
df = pd.DataFrame({'COL1':['text', 1,2],
'COL2':[1,2,0]})
def color(x):
c1 = 'background-color: red'
c2 = 'background-color: green'
c3 = 'background-color: yellow'
c = ''
s = pd.to_numeric(df['COL1'], errors='coerce')
m1 = s.isna() & df['COL1'].notna()
m2 = s.ge(df['COL2'])
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
df1['COL1'] = np.select([m1, m2], [c1, c2], default=c3)
return df1
df.style.apply(color,axis=None).to_excel('format_file.xlsx', index=False, engine='openpyxl')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/315289.html
