2 回答

TA貢獻1815條經驗 獲得超6個贊
附加["Sales"].iloc[0]
到過濾器表達式以直接獲取M
和 的值F
,然后將這些更改print()
也投影到函數中:
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 %
說明:
df.loc[df['Gender'] == 'M']
是一個數據框;"Sales"
通過附加["Sales"]
您獲得的系列(僅包含 1 個元素)來選擇列,并且通過附加,
.iloc[0]
您可以獲得該系列的第一個(=唯一一個)元素。
筆記:
您可以使用 f-string (對于 Python 3.6+)或.format()
調整輸出的方法,例如
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貢獻1827條經驗 獲得超8個贊
好的,您希望能夠直接按性別對您的銷售進行索引(使用.loc[]),因此我們讀取您的數據幀以index_col=[0]將索引設置為Gender列,然后squeeze=True將剩余的 1 列數據幀減少為一個系列。
然后我使用 f 字符串進行格式化。請注意,我們可以將表達式內聯到 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%
...如果您想更進一步并減少 df -> Series -> dict,請執行sl.to_dict(),現在您sl['M']/sl['F']可以像您可能想要的那樣直接引用(顯然我們失去了 Series 的所有豐富方法。)
添加回答
舉報