以百分比显示Pandas列

sy5wg1nm  于 2023-06-20  发布在  其他
关注(0)|答案(1)|浏览(265)

我用yfinance下载了属性'grossMargins'到Pandas数据框架中,该列的格式为0.3646。在内部,它应该用于进一步计算,但它应该显示为36.46%。我怎样才能让这一切发生?
下面是一个代码的小例子:

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)
but5z9lq

but5z9lq1#

如果您只处理一列(毛利),或者不介意将相同的格式应用于所有浮点值,下面的代码应该可以工作。如果你只需要格式化数据框中的一个列,你可能需要将值转换为字符串(因为你提到这是一个要求,所以进一步的计算会中断)。后一种情况的选择是简单地制作数据框的副本,格式化该副本以供显示,但保留原始数据以供计算。我无法让类似问题中提到的df.style.format()方法工作,可能是由于Pandas版本。

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)

生产:

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

相关问题