猿问

如何在 Python 中打印语句以显示 Pandas Dataframe 上数学运算的结果?

因此,我有一个按性别划分的简单销售额汇总数据框,内容如下:


Gender |    Sales

___________________

M      |    25

F      |    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:对象 %


请问想法?我是一个非常初学者,很抱歉有这样一个基本的查询!


暮色呼如
浏览 126回答 2
2回答

红糖糍粑

附加["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%

斯蒂芬大帝

好的,您希望能够直接按性别对您的销售进行索引(使用.loc[]),因此我们读取您的数据帧以index_col=[0]将索引设置为Gender列,然后squeeze=True将剩余的 1 列数据帧减少为一个系列。然后我使用 f 字符串进行格式化。请注意,我们可以将表达式内联到 f 字符串中:import pandas as pdfrom io import StringIO    dat = """\Gender |    Sales___________________M      |    25F      |    30"""sl = pd.read_csv(StringIO(dat), sep='\s*\|\s*', skiprows=[1], index_col=[0],    engine='python', squeeze=True)#               Sales# Gender            # M               25# F               30print(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 的所有丰富方法。)
随时随地看视频慕课网APP

相关分类

Python
我要回答