我想知道是否有任何可能的格式化模块,可用于格式化 Dataframe 输出。下面是代码:
import requests
import pandas as pd
pd.set_option("display.float_format", "{:.2f}".format)
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)
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
24 KEK $0.00 13.66% 1116.77% $17,577,074.00 7,545,426
4 DollarPepe $0.03 5.57% 329.57% $3.00 706,616
3 Diamond Pepe $0.00 19.68% 301.20% $10,737,494.00 2,116,732
21 FlokiPepe $0.00 31.55% 117.41% $1,446,299.00 1,475,708
所需产量:#--使用了markdown(),但不知何故改变了数字格式输出
| | Name | Price | 1h | 24h | MarketCap | Volume |
|---:|:----------------|:----------------|:-------|:--------|:---------------|:------------|
| 0 | DollarPepe | $0.02752 | 22.64% | 336.25% | $3 | $456,913 |
| 1 | Billy Token | $0.00002822 | 41.69% | 75.80% | $1,958,942 | $6,999,241 |
| 2 | JEFF | $0.1946 | 4.42% | 226.18% | $19,458,328 | $19,744,583 |
| 3 | PUG AI | $0.00000001459 | 10.80% | 15.84% | $1,459,428 | $239,454 |
1条答案
按热度按时间2izufjch1#
使用您提供的dataframe:
以下是使用Pandas str.pad和styler.hide的一种方法:
然后,隐藏索引和列标题: