2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊
附加["Sales"].iloc[0]
到過(guò)濾器表達(dá)式以直接獲取M
和 的值F
,然后將這些更改print()
也投影到函數(shù)中:
m_sales = df.loc[df['Gender'] == 'M']["Sales"].iloc[0] f_sales = df.loc[df['Gender'] == 'F']["Sales"].iloc[0] print('The mean gap in the amount sold is:', (f_sales - m_sales) / f_sales * 100, '%')
The mean gap in the amount sold is: 16.666666666666664 %
說(shuō)明:
df.loc[df['Gender'] == 'M']
是一個(gè)數(shù)據(jù)框;"Sales"
通過(guò)附加["Sales"]
您獲得的系列(僅包含 1 個(gè)元素)來(lái)選擇列,并且通過(guò)附加,
.iloc[0]
您可以獲得該系列的第一個(gè)(=唯一一個(gè))元素。
筆記:
您可以使用 f-string (對(duì)于 Python 3.6+)或.format()
調(diào)整輸出的方法,例如
print(f'The mean gap in the amount sold is: {(f_sales - m_sales) / f_sales * 100:.2f}%')
The mean gap in the amount sold is: 16.67%

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
好的,您希望能夠直接按性別對(duì)您的銷(xiāo)售進(jìn)行索引(使用.loc[]),因此我們讀取您的數(shù)據(jù)幀以index_col=[0]將索引設(shè)置為Gender列,然后squeeze=True將剩余的 1 列數(shù)據(jù)幀減少為一個(gè)系列。
然后我使用 f 字符串進(jìn)行格式化。請(qǐng)注意,我們可以將表達(dá)式內(nèi)聯(lián)到 f 字符串中:
import pandas as pd
from io import StringIO
dat = """\
Gender | Sales
___________________
M | 25
F | 30
"""
sl = pd.read_csv(StringIO(dat), sep='\s*\|\s*', skiprows=[1], index_col=[0],
engine='python', squeeze=True)
# Sales
# Gender
# M 25
# F 30
print(f"The mean gap in the amount sold is: {100.*(1 - sl.loc['M']/sl.loc['F']):.2f}%")
# The mean gap in the amount sold is: 16.67%
# ...but f-strings even have a datatype for percent: `:.2%`, so we don't need the `100. * (...)` boilerplate.
print(f"The mean gap in the amount sold is: {(1 - sl.loc['M']/sl.loc['F']):.2%}")
The mean gap in the amount sold is: 16.67%
...如果您想更進(jìn)一步并減少 df -> Series -> dict,請(qǐng)執(zhí)行sl.to_dict(),現(xiàn)在您sl['M']/sl['F']可以像您可能想要的那樣直接引用(顯然我們失去了 Series 的所有豐富方法。)
添加回答
舉報(bào)