将Pandas列显示为百分比

huangapple go评论211阅读模式
英文:

Display a Pandas column as percentage

问题

我已经使用yfinance将属性'grossMargins'下载到Pandas数据帧中,该列的格式为0.3646。在内部计算时,应该将其显示为36.46%。如何实现这一点?

这是一个小示例代码:

import yfinance as yf

# 定义公司的股票代码
ticker = "AAPL"

# 下载财务数据
company = yf.Ticker(ticker)
financials = company.financials

# 获取毛利率
gross_margins = financials['Gross Margins']

# 将毛利率保存到CSV文件中
gross_margins.to_csv('gross_margins.csv', header=True)

# 显示毛利率
print(gross_margins)

希望这对你有所帮助。

英文:

I have downloaded the attribute 'grossMargins' with yfinance into a Pandas dataframe, the column has the format 0.3646. Internally it should be used to calculate further, but it should be displayed as 36.46%. How can I make this happen?

Here is a little example of a code:

import yfinance as yf

# Define the ticker symbol of the company
ticker = "AAPL"

# Download the financial data
company = yf.Ticker(ticker)
financials = company.financials

# Get the gross margins
gross_margins = financials['Gross Margins']

# Save the gross margins to a CSV file
gross_margins.to_csv('gross_margins.csv', header=True)

# Display the gross margins
print(gross_margins)

答案1

得分: 1

以下是您要翻译的内容:

If you're only dealing with the one column (gross margins) or don't mind the same formatting being applied to all float values, the code below should work. If you need to format just a single column in your dataframe, you may need to convert the values to a string (making further calculations break, since you mentioned this is a requirement). An option for this latter case would be to simply make a copy of the dataframe, format that copy for display, but keep the original for calculations. I couldn't get the `df.style.format()` methods mentioned in similar questions to work, possibly due to Pandas version.

import pandas as pd
# pd version == 2.0.1

margin_data = {"margins":[0.3646, 0.2584, 0.8954]}
my_df = pd.DataFrame(margin_data)

# What you were printing before
print("Old formatting")
gross_margins = my_df['margins']
print(gross_margins)

# Apply new formatting to all floats
print("\nNew formatting")
pd.options.display.float_format = '{:.2%}'.format
gross_margins = my_df['margins']
print(gross_margins)

# Confirm values are still what you expect
print("\nValues")
print(my_df['margins'].iloc[0])

# Apply formatting to only one column, but makes 
# values a string instead of float
print("\nString formatting single column")
margin_data["more data"] = [1,2,3]
my_df2 = pd.DataFrame(margin_data)
my_df2['margins'].map('{:.2%}'.format)
print(my_df2)

Produces:

Old formatting
0 0.3646
1 0.2584
2 0.8954
Name: margins, dtype: float64

New formatting
0 36.46%
1 25.84%
2 89.54%
Name: margins, dtype: float64

Values
0.3646

String formatting single column
margins more data
0 36.46% 1
1 25.84% 2
2 89.54% 3


<details>
<summary>英文:</summary>

If you&#39;re only dealing with the one column (gross margins) or don&#39;t mind the same formatting being applied to all float values, the code below should work. If you need to format just a single column in your dataframe, you may need to convert the values to a string (making further calculations break, since you mentioned this is a requirement). An option for this latter case would be to simply make a copy of the dataframe, format that copy for display, but keep the  original for calculations. I couldn&#39;t get the `df.style.format()` methods mentioned in similar questions to work, possibly due to Pandas version.

    import pandas as pd
    # pd version == 2.0.1
    
    margin_data = {&quot;margins&quot;:[0.3646, 0.2584, 0.8954]}
    my_df = pd.DataFrame(margin_data)
    
    # What you were printing before
    print(&quot;Old formatting&quot;)
    gross_margins = my_df[&#39;margins&#39;]
    print(gross_margins)
    
    # Apply new formatting to all floats
    print(&quot;\nNew formatting&quot;)
    pd.options.display.float_format = &#39;{:.2%}&#39;.format
    gross_margins = my_df[&#39;margins&#39;]
    print(gross_margins)
    
    # Confirm values are still what you expect
    print(&quot;\nValues&quot;)
    print(my_df[&#39;margins&#39;].iloc[0])
    
    # Apply formatting to only one column, but makes 
    # values a string instead of float
    print(&quot;\nString formatting single column&quot;)
    margin_data[&quot;more data&quot;] = [1,2,3]
    my_df2 = pd.DataFrame(margin_data)
    my_df2[&#39;margins&#39;].map(&#39;{:.2%}&#39;.format)
    print(my_df2)

Produces:

    Old formatting
    0    0.3646
    1    0.2584
    2    0.8954
    Name: margins, dtype: float64
    
    New formatting
    0   36.46%
    1   25.84%
    2   89.54%
    Name: margins, dtype: float64
    
    Values
    0.3646
    
    String formatting single column
       margins  more data
    0   36.46%          1
    1   25.84%          2
    2   89.54%          3

</details>



huangapple
  • 本文由 发表于 2023年6月13日 05:56:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定