pandas 如何在dataframe中格式化数值

hgtggwj0  于 2023-05-12  发布在  其他
关注(0)|答案(2)|浏览(175)

我想把pandas的dataframe结果格式化为float。下面的代码以科学符号显示值。任何想法如何纠正将是有益的。
生成输出的代码:

import requests
import pandas as pd

url = "https://coinmarketcap.com/new/"
page = requests.get(url,headers={'User-Agent': 'Mozilla/5.0'}, timeout=1)
pagedata = page.text
usecols = ["Name", "Price", "1h", "24h", "MarketCap", "Volume"]#, "Blockchain"]

df = pd.read_html(pagedata)[0] #Checking table
df[["Name", "Symbol"]] = df["Name"].str.split(r"\d+", expand=True)
df = df.rename(columns={"Fully Diluted Market Cap": "MarketCap"})[usecols]

numcols = df.columns[df.columns != 'Name']
df[numcols] = df[numcols].apply(lambda c:pd.to_numeric(c.str.replace(r'[^\d.]|(?<!\d)\.|\.(?!\d)', '', regex=True)))
df = df.sort_values('24h', ascending=False)

print (df)

电流输出:

Name         Price     1h     24h     MarketCap    Volume
0        DollarPepe  4.402000e-02  16.87  597.88  4.000000e+00    541219
12    Perry The BNB  5.442000e-08   2.90  519.49  1.144662e+07  25606468
2              JEFF  1.802000e-01   3.66  202.07  1.802032e+07  21195038
19              KEK  5.665000e-08  57.52  154.52  4.405980e+06   5925829
16        FlokiPepe  2.836000e-09  34.48  118.71  1.193154e+06   1394199
1       Billy Token  3.168000e-05  11.69   72.83  2.198928e+06   5389786

所需输出:

Name  Price         1h      24h        MarketCap        Volume
0        DollarPepe  $0.04     $17.72%  16.87%           $586.08         $4.0     
12    Perry The BNB  $0.00      $2.66%   $557%    $12,086,284.00  $25,525,925
2              JEFF  $0.18      $1.91%   $194%    $17,541,936.00  $21,178,793
19              KEK  $0.00     $57.80%   $221%     $5,560,854.00   $5,864,987
16        FlokiPepe  $0.00     $22.75%   $110%     $1,132,337.00   $1,382,867
1       Billy Token  $0.00     $14.31%    $72%     $2,235,948.00   $5,405,861
y53ybaqx

y53ybaqx1#

您不能使用display.float_format来影响Volume列的显示,因为它具有int64数据类型。您可以使用to_string方法,为每种列类型提供格式化程序列表:

formats = {
    'Price': '${:.2f}'.format,
    '1h': '{:.2f}%'.format,
    '24h': '{:.2f}%'.format,
    'MarketCap': '${:,.2f}'.format,
    'Volume': '{:,d}'.format
}
print(df.to_string(formatters=formats))

输出(用于示例数据):

Name Price     1h     24h      MarketCap     Volume
0      DollarPepe $0.04 16.87% 597.88%          $4.00    541,219
12  Perry The BNB $0.00  2.90% 519.49% $11,446,620.00 25,606,468
2            JEFF $0.18  3.66% 202.07% $18,020,320.00 21,195,038
19            KEK $0.00 57.52% 154.52%  $4,405,980.00  5,925,829
16      FlokiPepe $0.00 34.48% 118.71%  $1,193,154.00  1,394,199
1     Billy Token $0.00 11.69%  72.83%  $2,198,928.00  5,389,786
idv4meu8

idv4meu82#

您可以尝试添加这一行。这确保float的全局格式为2位小数。

pd.set_option('display.float_format', '{:.2f}'.format)

相关问题