Python Pandas-如何提取字符串中一系列字符的左侧
我们有:Python Pandas-如何提取字符串中一系列字符的左侧,python,regex,pandas,dataframe,Python,Regex,Pandas,Dataframe,我们有: def get_prices(): prices = pd.read_json("https://api.binance.com/api/v1/ticker/allPrices") prices_df = pd.DataFrame(prices) prices_df["Asset"] = "??" prices_df["Quote"] = prices_df["symbol"].str.extract(r"(USDT|BTC|ETH|BNB)$")
def get_prices():
prices = pd.read_json("https://api.binance.com/api/v1/ticker/allPrices")
prices_df = pd.DataFrame(prices)
prices_df["Asset"] = "??"
prices_df["Quote"] = prices_df["symbol"].str.extract(r"(USDT|BTC|ETH|BNB)$")
return prices_df
退回此邮件:
price symbol Asset Quote
0 0.0578730 ETHBTC ?? BTC
1 0.0105800 LTCUSDT ?? USDT
2 0.0019219 NBBTC ?? BTC
3 0.0038840 NEOBNB ?? BNB
4 0.0157500 QTUMETH ?? ETH
这里的符号是由资产+报价组成的一对,没有任何分隔,每个符号可以有不同的长度。但我们知道报价符号只能是4:USDT、BTC、ETH、BNB
如何在数据框中定义资产列?您可以使用正则表达式来提取前缀,给出所有可能后缀的列表:
pattern = '(\w+)(USDT|BTC|ETH|BNB)$'
df[['Asset','Quote']] = df['symbol'].str.extract(pattern)
更新了答案以同时计算两列。