[英]Intersection of rows of a Dataframe based on the value in a column in the dataframe
[英]Style rows of a dataframe based on column value
我有一個 csv 文件,我正在嘗試將其讀入 dataframe 並在 jupyter 筆記本中設置樣式。 csv文件數據為:
[[' ', 'Name', 'Title', 'Date', 'Transaction', 'Price', 'Shares', '$ Value'],
[0, 'Sneed Michael E', 'EVP, Global Corp Aff & COO', 'Dec 09', 'Sale', 152.93, 54662, 8359460],
[1, 'Wengel Kathryn E', 'EVP, Chief GSC Officer', 'Sep 02', 'Sale', 153.52, 16115, 2473938],
[2, 'McEvoy Ashley', 'EVP, WW Chair, Medical Devices', 'Jul 28', 'Sale', 147.47, 29000, 4276630],
[3, 'JOHNSON & JOHNSON', '10% Owner', 'Jun 30', 'Buy', 17.00, 725000, 12325000]]
我的目標是設置行的背景顏色,以便如果 Transaction 列的值為“Buy”,則該行為綠色,如果 Transaction 列的值為“Sale”,則為紅色。
我試過的代碼是:
import pandas as pd
data = pd.read_csv('/Users/broderickbonelli/Desktop/insider.csv', index_col='Unnamed: 0')
def red_or_green():
if data.Transaction == 'Sale':
return ['background-color: red']
else:
return ['background-color: green']
data.style.apply(red_or_green, axis=1)
display(data)
當我運行代碼時,它會輸出一個沒有樣式的電子表格,而不會給我一個錯誤代碼:
我不太確定自己做錯了什么,我已經嘗試了多種不同的方法,但似乎無法讓它發揮作用。 任何幫助,將不勝感激!
嘗試
data['background-color'] = data.apply(lambda x: red_or_green(x.Transaction), axis=1)
def red_or_green(transaction):
if transaction == 'Sale':
return 'red'
else:
return 'green'
或者您可以使用 map:
data['background-color'] = data.Transaction.map(red_or_green)
此答案的修改:
def red_or_green(row):
if row.Transaction == 'Sale':
return pd.Series('background-color: red', row.index)
else:
return pd.Series('background-color: green', row.index)
styled_table = df.style.apply(red_or_green, axis=1)
如果要在條件匹配時比較整行,以下比 apply on axis=1 更快,我們在整個 Z6A8064B5DF4794555500553C47C55057DZ 上使用樣式:
def red_or_green(dataframe):
c = dataframe['Transaction'] == 'Sale'
a = np.where(np.repeat(c.to_numpy()[:,None],dataframe.shape[1],axis=1),
'background-color: red','background-color: green')
return pd.DataFrame(a,columns=dataframe.columns,index=dataframe.index)
df.style.apply(red_or_green, axis=None)#.to_excel(.....)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.