我想把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
2条答案
按热度按时间y53ybaqx1#
您不能使用
display.float_format
来影响Volume
列的显示,因为它具有int64
数据类型。您可以使用to_string
方法,为每种列类型提供格式化程序列表:输出(用于示例数据):
idv4meu82#
您可以尝试添加这一行。这确保float的全局格式为2位小数。