我试图自己解决这个问题,但我已经走进了死胡同。我正在尝试从我创建的函数返回一个字符串,该函数引用从函数中先前创建的 pandas 数据帧派生的数量,并且我希望每个变量引用显示为它自己的行作为输出:
net_winnings = all_invest_df['Payout'].sum()-all_invest_df['Investment'].sum()
return f"""Invested Amount: {all_invest_df['Investment'].sum()}
Payout Amount: {all_invest_df['Payout'].sum()}
Net Winnings: {net_winnings}"""
我想看到的是:
投资金额:xxxxx
支付金额:xxxxx
净奖金:xxxxx
但这是我当前的输出:
'投资金额:20680 支付金额:25442.31574810885 净奖金:4762.315748108849'
任何解决此问题的想法将不胜感激。谢谢。
textwrap.dedent
,这样任何行都没有前导空格:
import textwrap
import pandas as pd
def get_financial_summary(all_invest_df: pd.DataFrame) -> str:
net_winnings = all_invest_df['Payout'].sum() - all_invest_df['Investment'].sum()
return textwrap.dedent(f"""\
Invested Amount: {all_invest_df['Investment'].sum()}
Payout Amount: {all_invest_df['Payout'].sum()}
Net Winnings: {net_winnings}
""")
all_invest_df = pd.DataFrame(data={
'Investment': [1000, 1500, 1200],
'Payout': [1800, 2300, 1600],
})
print(all_invest_df)
print(get_financial_summary(all_invest_df))
输出:
Investment Payout
0 1000 1800
1 1500 2300
2 1200 1600
Invested Amount: 3700
Payout Amount: 5700
Net Winnings: 2000