这是我的代码:
import pandas as pd
import requests
url = "https://www.coingecko.com/en/coins/recently_added?page=1"
df = pd.read_html(requests.get(url).text, flavor="bs4")
df = pd.concat(df).drop(["Unnamed: 0", "Unnamed: 1"], axis=1)
df.to_csv("your_table.csv", index=False)
names = df["Coin"].str.rsplit(n=2).str[0].str.lower()
coins=names.replace(" ", "-")
print(coins)印刷品仍在印刷带有空格的硬币。我想用破折号(-)代替空格。有人能帮忙吗?
发布于 2021-06-10 12:02:54
您可以添加参数regex=True以使其工作:
coins = names.replace(" ", "-", regex=True)原因是对于.replace()函数,当替换没有regex=True的字符串时,它会查找与regex=True完全匹配的(默认为regex=False):
str:与 to_replace完全匹配的字符串将被替换为值 regex:regexs匹配的to_replace将被替换为值
因此,除非要替换的字符串仅包含一个空格(没有其他字符),否则将无法匹配要替换的字符串。因此,没有regex=True的代码就没有结果。
或者,您也可以使用.str.replace()而不是.replace()。
coins = names.str.replace(" ", "-").str.replace() 不需要精确匹配的和部分字符串的匹配,不管是regex=True还是regex=False。
结果:
print(coins)
0 safebreastinu
1 unicly-bored-ape-yacht-club-collection
2 bundle-dao
3 shibamax
4 swapp
...
95 apollo-space-token
96 futurov-governance-token
97 safemoon-inu
98 x
99 black-kishu-inu
Name: Coin, Length: 100, dtype: objecthttps://stackoverflow.com/questions/67920662
复制相似问题