亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Python 中打印語句以顯示 Pandas Dataframe 上數學運算的結果?

如何在 Python 中打印語句以顯示 Pandas Dataframe 上數學運算的結果?

暮色呼如 2023-10-25 10:39:49
因此,我有一個按性別劃分的簡單銷售額匯總數據框,內容如下:Gender |    Sales___________________M      |    25F      |    30我現在想要做的就是在 Python 中返回一行內容:銷售金額的平均差距為 16.67%這只是 30 - 25 除以 30,再乘以 100;我想在最后有一個 % 符號。我努力了:m_sales = df.loc[df['Gender'] == 'M']f_sales = df.loc[df['Gender'] == 'F']print('The mean gap in the amount sold is:', m_sales['Sales'] - f_sales['Sales'] / m_sales['Sales'] * 100, '%')不幸的是這不起作用。我得到:銷售金額的平均差距為: 0 NaN 1 NaN 名稱:銷售額,dtype:對象 %請問想法?我是一個非常初學者,很抱歉有這樣一個基本的查詢!
查看完整描述

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%


查看完整回答
反對 回復 2023-10-25
?
斯蒂芬大帝

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 的所有豐富方法。)


查看完整回答
反對 回復 2023-10-25
  • 2 回答
  • 0 關注
  • 169 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號